- 定义条件对象
@Data
public class ComplexQueryDto {
private List<QueryDto> params=new ArrayList<>();
public ComplexQueryDto addParam(QueryDto queryDto){
this.params.add(queryDto);
return this;
}
}
- 定义查询对象
@Data
@Accessors(chain =true)
public class QueryDto {
private String filedName;
private String opt;
private String filedValue;
private String[] filedValues;
private String rel;
}
- 查询条件枚举
@Getter
public enum QueryOpt {
NOT_NULL("IS NOT NULL"),
IN("IN"),
NOT_IN("NOT IN"),
LIKE("LIKE"),
NOT_LIKE("NOT LIKE"),
EQ("="),
NE("!="),
GT(">"),
GE(">="),
LT("<"),
LE("<="),
BETWEEN("BETWEEN");
private final String seg;
public String getSeg() {
return seg;
}
QueryOpt(String seg) {
this.seg = seg;
}
}
- 查询关系枚举
@Getter
public enum QueryRel {
AND("AND"),
OR("OR"),
NOT("NOT");
private final String seg;
public String getSeg() {
return seg;
}
QueryRel(String seg) {
this.seg = seg;
}
}
- 编写条件拼接SQL
<sql id="complexQuery">
<if test="params != null and params.size() != 0">
<foreach item="param" index="index" collection="params">
AND ${param.filedName} ${param.opt}
<if test="param.opt == 'BETWEEN'">#{param.filedValues[0]} AND #{param.filedValues[0]}</if>
<if test="param.opt == 'IN'||param.opt == 'NOT IN'">
<foreach item="filedValue" index="index" collection="param.filedValues" open="(" separator="," close=")">
#{filedValue}
</foreach>
</if>
</foreach>
</if>
</sql>
<select id="??Query" resultMap="??">
SELECT
<include refid="div_Column_List"></include>
FROM
<include refid="table"></include>
<include refid="complexQuery"></include>
</select>