MyBatis基础入门《十八》动态SQL(if-where)
描述:
代码是在《MyBatis基础入门《十七》动态SQL》基础上进行改造的,不再贴所有代码,仅贴改动过的代码。
ClientMapper.xml文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.charles.mapper.ClientMapper"> <resultMap type="com.charles.entity.TblClient" id="tblClientID">
<id property="cid" column="id" />
<result property="cname" column="client_name"/>
<result property="caddress" column="client_address"/>
<result property="cbirthday" column="client_birthday"/>
</resultMap> <select id="getClientAll" resultMap="tblClientID">
SELECT
id ,
client_name ,
client_address ,
client_birthday
FROM tbl_client
WHERE 1 = 1
<if test="null != cname and '' != cname ">
AND client_name like CONCAT('%',#{cname},'%')
</if>
<if test="null != address and '' != address ">
AND client_address = #{address}
</if>
</select> </mapper>
ClientMapper.java
package com.charles.mapper; import java.util.List; import org.apache.ibatis.annotations.Param; import com.charles.entity.TblClient; public interface ClientMapper { /**
* 注意这个名字,必须要和ClientMapper.xml文件中的select标签id属性值一样。
* @param name
* @param caddress
* @return List<TblClient> 集合
*/
public List<TblClient> getClientAll(@Param("cname") String name, @Param("address") String caddress); }
JunitSelect.java
package com.charles.junit; import java.util.List; import org.apache.ibatis.session.SqlSession;
import org.junit.Test; import com.charles.entity.TblClient;
import com.charles.mapper.ClientMapper;
import com.charles.util.MyBatisUtil; public class JunitSelect { @Test
public void selectif() { /** 1. 获取SQLSession **/
SqlSession session = MyBatisUtil.getSqlSession(); /** 2. 调度方法,从数据库中获取数据 **/
List<TblClient> list = session.getMapper(ClientMapper.class).getClientAll("缘","上海"); /** 3. 关闭SQLSession **/
MyBatisUtil.closeSqlSession(session); for (TblClient client : list) {
System.out.println(client.getCid() + "\t" + client.getCname() + "\t" + client.getCaddress() + "\t"
+ client.getCbirthday());
}
}
}
测试结果:
》》》》》 改造ClientMapper.xml 使用where标签
>> where标签用途
-> 简化SQL语句中where条件判断
-> 智能处理 and 和 or
ClientMapper.xml文件改造前:
ClientMapper.xml文件改造后:
测试代码(给的值,均为空):
测试结果:
如有问题,欢迎纠正!!!
如有转载,请标明源处:https://www.cnblogs.com/Charles-Yuan/p/9903734.html