[TOC]
使用MyBatis,所有的Dao層方法繼承基類BaseMapper<T>
一页藻、使用<script></script>
腳本包裹
第一種方式:使用
<script></script>
進(jìn)行包裹桨嫁,像在xml中寫sql語句一樣實(shí)現(xiàn)動(dòng)態(tài)SQL
1、使用<if></if>
標(biāo)簽份帐,實(shí)現(xiàn)關(guān)鍵詞模糊查找
@Mapper
public interface CompanyMapper extends BaseMapper<CompanyEntity> {
// 分頁查詢
@Select("<script>" +
" select t.*,a.name_cn as company_name" +
" from t_company t " +
" join t_customer_company a on t.company_id=a.id" +
" where <![CDATA[t.status <> 2]]>" +
" <if test='nameCn != null and nameCn.trim() != ""'>" +
" AND t.name_cn like CONCAT('%',#{nameCn},'%')" +
" </if>" +
" </script>")
IPage<CompanyEntity> selectCompanybyPage(Page<CompanyEntity> page,
@Param("nameCn") String nameCn);
}
- 1璃吧、如果涉及不等于等操作,可以使用
<![CDATA[要包裹的內(nèi)容]]>
將其包裹废境。- 2畜挨、對(duì)字符串進(jìn)行null判斷與空串的判斷可參照
<if test='nameCn != null and nameCn.trim() != ""'>
方式,具體可參考動(dòng)態(tài)SQL之噩凹、條件判斷巴元。
1.1、使用<where></where>
標(biāo)簽驮宴,實(shí)現(xiàn)關(guān)鍵詞模糊查詢進(jìn)階
由
<where></where>
包裹的<if></if>
標(biāo)簽中的SQl語句逮刨,除第一個(gè)and可省略不寫外,其他均需要寫堵泽。
@Select("<script>" +
" select t.* from t_log t" +
" <where>" +
" <if test='typeName!= null'>" +
" and t.type_name like CONCAT('%',#{typeName},'%')" +
" </if>" +
" <if test='typeCode!= null'>" +
" and t.type_code like CONCAT('%',#{typeCode},'%')" +
" </if>" +
" </where>" +
" </script>")
IPage<LogEntity> selectLogByPage(Page<LogEntity> page,
@Param("typeName") String typeName,
@Param("typeCode") String typeCode);
1.2修己、查詢語句中出現(xiàn)大于小于的另一種方式寫法
當(dāng)注解SQL語句中出現(xiàn)日期的大于等于和小于等于判斷時(shí),如果未使用
<![CDATA[內(nèi)容]]>
進(jìn)行包裹迎罗,則將小于等于轉(zhuǎn)譯為lt;=
(或者將大于等于轉(zhuǎn)義為:>=
)
原則是:SQL注解語句中只能出現(xiàn)同方向的大于或者我小于睬愤。
@Select("<script>" +
" select t.* from t_user_plan t" +
" where t.type=0" +
" <if test='startTime != null'>" +
" AND t.effective_date >= #{startTime} " +
" </if>" +
" <if test='endTime != null'>" +
" AND t.effective_date <= #{endTime} " +
" </if>" +
" </script>"
)
IPage<UserPlanEntity> selectUserPlanByPage(Page<UserPlanEntity> page,
@Param("startTime") LocalDate startTime,
@Param("endTime") LocalDate endTime);
2、使用<foreach></foreach>
標(biāo)簽佳谦,實(shí)現(xiàn)id列表查詢
// 根據(jù)id集合查詢所有對(duì)象
@Select("<script>" +
" select t.* from t_user t " +
" where t.id in" +
" <foreach collection='ids' item='id' open='(' separator=',' close=')'>" +
" #{id}" +
" </foreach>" +
" </script>")
List<UserEntity> selectAllUserbyIds(@Param("ids") List<String> ids);
3戴涝、使用<foreach></foreach>
標(biāo)簽,實(shí)現(xiàn)批量插入
/**
* 批量插入
* @param list
* @return
*/
@Insert("<script>" +
" INSERT INTO t_position(sate,type,zone_id,time,lon,lat,height)VALUES" +
" <foreach collection='list' item='entity' separator=','> " +
" (#{entity.sate},#{entity.type},#{entity.zoneId},#{entity.time},#{entity.lon},#{entity.lat},#{entity.height})" +
" </foreach> " +
" </script>")
boolean insertBatch(@Param("list") List<PositionEntity> list);
附上yml中需要配置項(xiàng)特別說明:需要在url中添加rewriteBatchedStatements=true,否則批量插入不生效啥刻!
spring:
config:
activate:
on-profile: dev
datasource:
driverClassName: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/mysql_name?zeroDateTimeBehavior=convertToNull&autoReconnect=true&tinyInt1isBit=false&useSSL=false&allowMultiQueries=true&useUnicode=true&characterEncoding=utf8&allowPublicKeyRetrieval=true&rewriteBatchedStatements=true
username: root
password: 123456
以上
on-profile
寫法奸鸯,使用MP版本為:3.4.3.4
4、使用<set></set>
標(biāo)簽可帽,實(shí)現(xiàn)字段更新
@Update("<script>" +
" update radius.t_user_plan" +
" <set>" +
" <if test='plan.state != null'>" +
" state = #{plan.state}," +
" </if>" +
" <if test='plan.effectiveDate != null'>" +
" effective_date=#{plan.effectiveDate}," +
" </if>" +
" <if test='plan.expireDate != null'>" +
" expire_date=#{plan.expireDate}," +
" </if>" +
" <if test='plan.dataLimit != null'>" +
" data_limit=#{plan.dataLimit}," +
" </if>" +
" </set>" +
" where user_plan_id in" +
" <foreach collection='ids' item='id' open='(' separator=',' close=')'>" +
" #{id}" +
" </foreach>" +
" and state = 0" +
" and (YEAR(effective_date)=YEAR(CURTIME()) and MONTH(effective_date)=MONTH(CURTIME()))" +
" </script>")
int updateUserByIds(@Param("ids") List<Long> ids,
@Param("plan") Plan plan);
5娄涩、使用對(duì)象集合來進(jìn)行更新
@Update("<script>" +
" update t_user" +
" set balance = #{balance}" +
" where id in" +
" <foreach collection='list' item='one' open='(' separator=',' close=')'>" +
" #{one.id}" +
" </foreach>" +
" </script>"
)
int updateBillPubAccountByIds(@Param("list") List<User> list,
@Param("balance") Integer balance);
6、插入或更新(單條記錄)
由于MyBatis Plus升級(jí)到3.5.7后映跟,繼承自BaseMapper后蓄拣,其父類中存在insertOrUpdate更新單條或多條記錄的重載方法,經(jīng)測試努隙,其更新或插入依賴的是主鍵id球恤,不能很好的符合要求,以下重寫了insertOrUpdate實(shí)現(xiàn)根據(jù)自定義唯一性索引進(jìn)行更新
SQL詳情
/**
* 插入或更新數(shù)據(jù)信息
* key值:user_id(需要在數(shù)據(jù)庫中將這字段標(biāo)注為唯一索引)
*
* @param entity 待插入或更新的實(shí)體對(duì)象
*/
@Override
@Insert("<script>" +
" INSERT INTO t_user_task(user_id,user_type,priority,slice_id,task_type,des_user_id,res_req,state,sid,bid,flag,sid2,bid2) VALUES " +
" (#{entity.userId},#{entity.userType},#{entity.priority},#{entity.sliceId},#{entity.taskType},#{entity.desUserId},#{entity.resReq},#{entity.state},#{entity.sid},#{entity.bid},#{entity.flag},#{entity.sid2},#{entity.bid2})" +
" on duplicate key update" +
" user_id=values(user_id)," +
" user_type=values(user_type)," +
" priority=values(priority)," +
" slice_id=values(slice_id)," +
" task_type=values(task_type)," +
" des_user_id=values(des_user_id)," +
" res_req=values(res_req)," +
" state=values(state)," +
" sid=values(sid)," +
" bid=values(bid)," +
" flag=values(flag)," +
" sid2=values(sid2)," +
" bid2=values(bid2)" +
" </script>")
boolean insertOrUpdate(@Param("entity") UserTask entity);
設(shè)置該表中user_id為唯一索引
7荸镊、插入或更新(多條記錄)
/**
* 批量插入或更新數(shù)據(jù)信息
* key值:user_id(需要在數(shù)據(jù)庫中將這字段標(biāo)注為唯一索引)
*
* @param list 待插入或更新的實(shí)體集合
* @return 返回影響的記錄數(shù)
*/
@Insert("<script>" +
" <foreach collection='list' item='entity' separator=';'>" +
" INSERT INTO t_user_task(user_id,user_type,priority,slice_id,task_type,des_user_id,res_req,state,sid,bid,flag,sid2,bid2) VALUES " +
" (#{entity.userId},#{entity.userType},#{entity.priority},#{entity.sliceId},#{entity.taskType},#{entity.desUserId},#{entity.resReq},#{entity.state},#{entity.sid},#{entity.bid},#{entity.flag},#{entity.sid2},#{entity.bid2})" +
" on duplicate key update" +
" user_id=values(user_id)," +
" user_type=values(user_type)," +
" priority=values(priority)," +
" slice_id=values(slice_id)," +
" task_type=values(task_type)," +
" des_user_id=values(des_user_id)," +
" res_req=values(res_req)," +
" state=values(state)," +
" sid=values(sid)," +
" bid=values(bid)," +
" flag=values(flag)," +
" sid2=values(sid2)," +
" bid2=values(bid2)" +
" </foreach>" +
" </script>")
int insertOrUpdateBatch(@Param("list") List<UserTask> list);
注意:多條記錄進(jìn)行
插入或更新
操作時(shí)咽斧,返回的int結(jié)果,經(jīng)過測試躬存,并非是影響的記錄數(shù)张惹。
二、使用if()(類三目運(yùn)算)
第二種方式:使用if(執(zhí)行條件,true操作,false操作)進(jìn)行岭洲。
使用此方法時(shí),注意where條件后面根據(jù)需要加上1=1
1盾剩、實(shí)現(xiàn)關(guān)鍵詞查詢
@Mapper
public interface UserMapper extends BaseMapper<UserEntity> {
// 根據(jù)id查詢、根據(jù)name模糊查詢
@Select("select t.id,t.login_name,t.name,b.name as login_station_name" +
" from t_user t" +
" left join t_remote_station b on t.login_station_id=b.id" +
" WHERE 1=1" +
" and if(#{id} is null,1=1,t.id=#{id})" +
" and if(#{name} is null,1=1,t.name like CONCAT('%',#{name},'%'))")
List<UserEntity> selectUserListByPage(Page<UserEntity> page,
@Param("id") Long id,
@Param("name") String name);
}
總結(jié)
1侥锦、使用以上任意一種方式都能實(shí)現(xiàn)比較復(fù)雜的動(dòng)態(tài)SQL,建議使用第一種方式德挣。
2恭垦、無論使用第一種還是第二種,都存在隱患番挺,即屯掖,當(dāng)傳入?yún)?shù)為空的時(shí)候玄柏,可能會(huì)造成全表查詢。解決的辦法是:在業(yè)務(wù)實(shí)現(xiàn)層對(duì)參數(shù)進(jìn)行非空判斷贴铜,如果為空粪摘,則賦null值瀑晒。
3徘意、如果涉及到在同一個(gè)數(shù)據(jù)庫實(shí)例中的跨庫查詢時(shí),表名前需加上數(shù)據(jù)庫名稱即可玖详,如:數(shù)據(jù)庫名.表名(中間有一點(diǎn))勤讽。
引文
文章參考
- mybatis @Select注解中如何拼寫動(dòng)態(tài)sql
- MyBatis在注解上使用動(dòng)態(tài)SQL(@select使用if)
- mybatis @Select注解中如何拼寫動(dòng)態(tài)sql
- Mybatis 使用注解和Provider類實(shí)現(xiàn)動(dòng)態(tài)條件查詢
- 動(dòng)態(tài)SQL之、條件判斷
XML轉(zhuǎn)義字符
語義 | 字符 | 轉(zhuǎn)義字符 |
---|---|---|
小于號(hào) | < | < |
大于號(hào) | > | > |
和 | & | & |
單引號(hào) | ' | ' |
雙引號(hào) | " | " |