mybatis使用註解替代xml配置,動態生成Sql
mybatis使用註解替代xml配置時,遇到判斷條件是否為null或者為空時,@Select很難搞定,不知道怎麽辦?
mybatis3中增加了使用註解來配置Mapper的新特性,使用 SelectProvider來動態生成sql。
典型的使用場景
1. [email protected]
[email protected],均無參數:
UserMapper.java:
2 @ResultMap("userMap")
2 return "select * from user";
3 } [email protected]
[email protected]@SelectProvider
@SelectProvider是聲明在方法基本上的,這個方法定義在Mapper對應的的interface上。1 public interface UserMapper {
3 @ResultMap("userMap")
4 public User getUser(long userId);
5 } 上例中是個很簡單的Mapper接口,其中定義了一個方法:getUser,這個方法根據提供的用戶id來查詢用戶信息,並返回一個User實體bean。
這是一個很簡單很常用的查詢場景:根據key來查詢記錄並將結果封裝成實體bean。其中:
@SelectProvider註解用於生成查詢用的sql語句,[email protected]
@ResultMap註解用於從查詢結果集RecordSet中取數據然後拼裝實體bean。
@SelectProvide中type參數指定的Class類,必須要能夠通過無參的構造函數來初始化。
@SelectProvide中method參數指定的方法,必須是public的,返回值必須為String,可以為static。 1 public class SqlProvider {
2 public String selectUser(long userId) {
3 return "select * from user where userId=" + userId;
4 }
5 }
[email protected]@SelectProvide方法
對於只有一個參數的情況,可以直接使用,參見前面的getUser和selectUser。
但是,如果在getUser方法中,[email protected],那麽相應selectUser方法必須接受Map<String, Object>做為參數:
UserMapper.java:
2 @ResultMap("userMap")
3 public User getUser2(@Param("userId") long userId);
SqlProvider.java:
1 public String selectUser2(Map<String, Object> para) {2 return "select * from user where userId=" + para.get("userId");
3 }
[email protected]
在超過一個參數的情況下,@SelectProvide方法必須接受Map<String, Object>做為參數,
[email protected],[email protected],如下例中的userId;
[email protected],那麽參數在Map中以參數的順序為key,如下例中的password:
2 @ResultMap("userMap")
3 public User getUserCheck(@Param("userId") long userId, String password); SqlProvider.java:
1 public String selectUserCheck(Map<String, Object> para) {
2 return "select * from user where userId=" + para.get("userId") + " and password=‘" + para.get("1") + "‘";
3 }
4.一些限制
[email protected],不要使用重載,也就是說,不要使用方法名相同參數不同的方法,以避免發生詭異問題。 參考文獻: 【1】http://www.blogjava.net/dbstar/archive/2011/08/08/355825.html
mybatis使用註解替代xml配置,動態生成Sql