【Mybatis】动态SQL之choose标签
1、Pojo
package com.yczxyy.paperfree.dto.jhemr;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
/**
* @author potential
*/
@Data
public class JobEmrMonitor {
@ApiModelProperty(value = "监控代码编号")
private String MONITOR_ITEM_CODE;
@ApiModelProperty(value = "监控代码名称")
private String MONITOR_ITEM_NAME;
}
2、Dao
List<JobEmrMonitor> getMonitor1(JobEmrMonitor jobEmrMonitor);
3、Service
List<JobEmrMonitor> getMonitor1(JobEmrMonitor jobEmrMonitor);
4、ServiceImpl
@Override
public List<JobEmrMonitor> getMonitor1(JobEmrMonitor jobEmrMonitor) {
return dmsZhiKongRuleDao.getMonitor1(jobEmrMonitor);
}
5、xml配置文件
<select id="getMonitor1" parameterType="com.yczxyy.paperfree.dto.jhemr.JobEmrMonitor" resultType="com.yczxyy.paperfree.dto.jhemr.JobEmrMonitor">
select MONITOR_ITEM_CODE MONITOR_ITEM_CODE,
MONITOR_ITEM_NAME MONITOR_ITEM_NAME
from dms_monitor
<where>
<choose>
<when test="MONITOR_ITEM_NAME !=null">
MONITOR_ITEM_NAME like concat('%',#{MONITOR_ITEM_NAME},'%')
</when>
<when test="MONITOR_ITEM_CODE !=null">
MONITOR_ITEM_CODE like concat('%',#{MONITOR_ITEM_CODE},'%')
</when>
<when test="MONITOR_ITEM_CODE !=null and MONITOR_ITEM_NAME!=null">
and MONITOR_ITEM_NAME like concat('%',#{MONITOR_ITEM_NAME},'%')
</when>
<!-- <otherwise>-->
<!-- and MONITOR_ITEM_NAME like concat('%',#{MONITOR_ITEM_NAME},'%')-->
<!-- </otherwise>-->
</choose>
</where>
</select>
注意:
这里重点解释一下xml配置文件中的动态SQL含义。
1、首先是 where标签,where标签里面包含 就是查询的条件
2、接下来是choose标签,choose标签中的就是可供选择的条件
3、when标签 就是每一个查询条件 当满足第一个查询条件的时候,就直接开始查询了;如果第一个查询条件不满足,就来看第二个查询条件,若满足,就进行查询,程序结束;如都不符合,这里又分为两种情况:(1)when标签中的查询条件都不符合,但是又必须插入参数,那么就使用otherwise标签,来控制,使得必须有一个基本条件 即otherwise这个标签中的内容满足才可以进行查询,否则报错;(2)若when标签中的查询条件不符合,但是又不需要控制必要的参数,也就是说,即使不传入任何参数,那么也会有东西返回,即将表中内容全部返回。
6、Controller
@ApiOperation("监控代码/名称 字典2")
@PostMapping("getMonitorNameAndCode1")
public CommonResult getMonitorNameAndCode1(@Validated JobEmrMonitor jobEmrMonitor){
ArrayList<JobEmrMonitor> list = new ArrayList<>();
list=(ArrayList<JobEmrMonitor>) dmsZhiKongRuleService.getMonitor1(jobEmrMonitor);
return CommonResult.success(list);
}
7、测试
7.1 只输入MONITOR_ITEM_CODE
,会根据MONITOR_ITEM_CODE进行动态模糊查询,返回满足条件的内容。
7.2 只输入MONITOR_ITEM_NAME
,会根据MONITOR_ITEM_NAME进行模糊查询,返回满足条件的内容。
7.3 参数什么都不传 在什么都不传的情况下,依然会有返回值,即返回表中全部内容。