您的位置:首页 > 数据库 > SQL

MyBatis使用@SelectProvider拼接sql语句

2018-01-17 00:00 1916 查看
如果使用MyBatis注解方式写sql,又想要XML写法的判断入参拼接条件,可以通过@SelectProvider方式实现。

新建Provider

public class RateProvider {
private final String table_name = "rate_finish";

public String getFinishRate(Map<String, Object> para) {
String sql = "SELECT homework_type,device_type,`level`,finish_count,count,create_at FROM rate_finish ";
sql += "WHERE 1=1 ";
if (para.get("deviceType") != null && !StringUtils.isEmpty(para.get("deviceType").toString())) {
sql += "AND device_type = '" + para.get("deviceType").toString() + "' ";
}
if (para.get("homeworkType") != null && !StringUtils.isEmpty(para.get("homeworkType").toString())) {
sql += "AND homework_type = '" + para.get("homeworkType").toString() + "' ";
}
if (para.get("date") != null && !StringUtils.isEmpty(para.get("date").toString())) {
sql += "AND create_at = '" + para.get("date").toString() + "' ";
}
sql += "ORDER BY homework_type,device_type,`level`";
return sql;
}
}

这里的para会包含6个值,也就是2倍的入参参数,可以通过key方式或者index方式获取对应参数。

新建Entity

public class RateFinish extends AbstractModel {

private int id;
private String deviceType;
private String level;
private String finishCount;
private String count;
private String homeworkType;
private String createAt;

编写Mapper方法

@SelectProvider(type = RateProvider.class, method = "getFinishRate")
@Results({
@Result(property = "homeworkType", column = "homework_type"),
@Result(property = "deviceType", column = "device_type"),
@Result(property = "level", column = "level"),
@Result(property = "finishCount", column = "finish_count"),
@Result(property = "count", column = "count"),
@Result(property = "createAt", column = "create_at")
})
List<RateFinish> getFinishRate(
@Param("deviceType") String deviceType,
@Param("homeworkType") String homeworkType,
@Param("date") String date);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  MyBatis