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