MyBatis基礎入門《十八》動態SQL(if-where)
阿新 • • 發佈:2018-11-04
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_birthday21 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