使用MyBatis,所有的Dao层方法继承基类BaseMapper
一、使用脚本包裹
第一种方式:使用进行包裹,像在xml中写sql语句一样实现动态SQL
1、使用标签,实现关键词模糊查找
@Mapper
public interface CompanyMapper extends BaseMapper {
// 分页查询
@Select("
" select t.*,a.name_cn as company_name" +
" from t_company t " +
" join t_customer_company a on t.company_id=a.id" +
" where t.status <> 2" +
" " +
" AND t.name_cn like CONCAT('%',#{nameCn},'%')" +
" " +
" ")
IPage selectCompanybyPage(Page page,
@Param("nameCn") String nameCn);
}
1、如果涉及不等于等操作,可以使用将其包裹。
2、对字符串进行null判断与空串的判断可参照方式,具体可参考动态SQL之、条件判断。
1.1、使用标签,实现关键词模糊查询进阶
由包裹的标签中的SQl语句,除第一个and可省略不写外,其他均需要写。
@Select("
" select t.* from t_log t" +
" " +
" " +
" and t.type_name like CONCAT('%',#{typeName},'%')" +
" " +
" " +
" and t.type_code like CONCAT('%',#{typeCode},'%')" +
" " +
" " +
" ")
IPage selectLogByPage(Page page,
@Param("typeName") String typeName,
@Param("typeCode") String typeCode);
1.2、查询语句中出现大于小于的另一种方式写法
当注解SQL语句中出现日期的大于等于和小于等于判断时,如果未使用进行包裹,则将小于等于转译为lt;=(或者将大于等于转义为:>=)
原则是:SQL注解语句中只能出现同方向的大于或者我小于。
@Select("
" select t.* from t_user_plan t" +
" where t.type=0" +
" " +
" AND t.effective_date >= #{startTime} " +
" " +
" " +
" AND t.effective_date <= #{endTime} " +
" " +
" "
)
IPage selectUserPlanByPage(Page page,
@Param("startTime") LocalDate startTime,
@Param("endTime") LocalDate endTime);
2、使用标签,实现id列表查询
// 根据id集合查询所有对象
@Select("
" select t.* from t_user t " +
" where t.id in" +
" " +
" #{id}" +
" " +
" ")
List selectAllUserbyIds(@Param("ids") List ids);
3、使用标签,实现字段更新
@Update("
" update radius.t_user_plan" +
" " +
" " +
" state = #{plan.state}," +
" " +
" " +
" effective_date=#{plan.effectiveDate}," +
" " +
" " +
" expire_date=#{plan.expireDate}," +
" " +
" " +
" data_limit=#{plan.dataLimit}," +
" " +
" " +
" where user_plan_id in" +
" " +
" #{id}" +
" " +
" and state = 0" +
" and (YEAR(effective_date)=YEAR(CURTIME()) and MONTH(effective_date)=MONTH(CURTIME()))" +
" ")
int updateUserByIds(@Param("ids") List ids,
@Param("plan") Plan plan);
二、使用if()(类三目运算)
第二种方式:使用if(执行条件,true操作,false操作)进行。
使用此方法时,注意where条件后面根据需要加上1=1
1、实现关键词查询
@Mapper
public interface UserMapper extends BaseMapper {
// 根据id查询、根据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 selectUserListByPage(Page page,
@Param("id") Long id,
@Param("name") String name);
}
总结
1、使用以上任意一种方式都能实现比较复杂的动态SQL,建议使用第一种方式。
2、无论使用第一种还是第二种,都存在隐患,即,当传入参数为空的时候,可能会造成全表查询。解决的办法是:在业务实现层对参数进行非空判断,如果为空,则赋null值。
3、如果涉及到在同一个数据库实例中的跨库查询时,表名前需加上数据库名称即可,如:数据库名.表名(中间有一点)。