MyBatis?@Select注解介紹:基本用法與動態(tài)SQL拼寫方式
1、@Select注解基本用法
@Select注解的目的是為了取代xml中的select標簽,只作用于方法上面。
下面看一下@Select注解的源碼介紹:
@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface Select { ? ? String[] value(); }
從上述可以看到兩點信息:
(1)@Select注解只能修飾方法
(2)@Select注解的值是字符數組。
所以,@Select注解的用法是這樣的:
@Select({ "select * from xxx", "select * from yyy" }) Person selectPersonById(Integer id);
雖然@Select注解的值是字符數組,但是真正生效的應該是最后那條SQL語句。這一點請大家要留意一下。
2、@Select注解動態(tài)SQL拼寫
普通的字符串值,只能實現變量的替換功能,如下所示,
@Select("select * from t_person where id = #{id}") Person selectPersonById(Integer id);
如果要想實現復雜的邏輯判斷,則需要使用標簽,如下所示:
@Select("<script> select * from t_person where id = #{id}? <when test='address !=null'> and address = #{address}? </when> </script>") Person selectPersonById(Integer id);
其實,標簽并非是@Select注解專用的,其他的注解,例如@Insert,@Update等等,都可以使用的。
@Select動態(tài)參數參考
今天發(fā)現一個問題,使用標簽進行查詢語句的拼接時,逗號和引號老處理不好,所以在此記錄下,供以后參考
@Select("<script>" + " select * from tb_crowd_fund_person_record a,tb_crowd_fund_info b where b.id=a.crowd_fund_info_id " + " <if test='activeStatus != null and activeStatus != \"\"'> "+ " and b.active_status=#{activeStatus} " + " </if> " + " <if test='createUser != null and createUser != \"\"'> "+ " and a.create_user=#{createUser} " + " </if> " + "</script>") List<String> findByType(Map<String,String> map);
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
仿京東平臺框架開發(fā)開放平臺(包含需求,服務端代碼,SDK代碼)
現在開放平臺越來越多了,下面針對仿京東開放平臺框架,封裝自己的開放平臺,分享給大家。先感謝一下京東開放平臺的技術大佬們,下面從開放平臺需求,服務端代碼,SDK代碼三大塊進行分享2021-06-06