MyBatis之動态SQL-MyBatis學習03
Mybatis架構的搭建前面兩篇筆記中已經寫了,這裡就不寫了,這裡使用到了一個新的jar包,log4j,點選官網下載下傳
下載下傳完之後使用以下三個jar包,如圖所示:
![](https://img.laitimes.com/img/_0nNw4CM6IyYiwiM6ICdiwiIyVGduV2YfNWawNCM38FdsYkRGZkRG9lcvx2bjxiNx8VZ6l2cs0TPB9UNNpWTyEFROBDOsJGcohVYsR2MMBjVtJWd0ckW65UbM5WOHJWa5kHT20ESjBjUIF2X0hXZ0xCMx81dvRWYoNHLrdEZwZ1Rh5WNXp1bwNjW1ZUba9VZwlHdssmch1mclRXY39CXldWYtlWPzNXZj9mcw1ycz9WL49zZuBnL0QDOwAjN0YTM3ATMxAjMwIzLc52YucWbp5GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.png)
并寫一個
log4j.propertise
資源檔案,寫完之後去mybatis核心配置檔案中加載一下
# Set root category priority to INFO and its only appender to CONSOLE.
log4j.rootCategory=INFO, CONSOLE
# log4j.rootCategory=INFO, CONSOLE, LOGFILE
#單獨設定SQL語句的輸出級别為DEBUG級别
#方法級别設定
#log4j.logger.com.mappers.DeptMapper.queryAll=DEBUG
#類級别
#log4j.logger.com.mappers.DeptMapper=DEBUG
#包級别
log4j.logger.com.mappers=DEBUG
# CONSOLE is set to be a ConsoleAppender using a PatternLayout.
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern= %m%n
# LOGFILE is set to be a File appender using a PatternLayout.
log4j.appender.LOGFILE=org.apache.log4j.FileAppender
log4j.appender.LOGFILE.File=D:/test.log
log4j.appender.LOGFILE.Append=true
log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout
log4j.appender.LOGFILE.layout.ConversionPattern=- %m %l%n
mybatis.xml
在如圖所示位置配置加載
log4j.properties
在上一篇筆記中,因為有不同的功能,是以寫了根據Id查找,查找全部等方法,使得代碼略顯臃腫,這裡可以使用動态SQL使得一些代碼共用,不用寫那麼多方法。
首先寫好對應的員工實體類:
Emp
,屬性名和資料庫中表的字段名一緻,再寫EmpMapper接口和對應的映射檔案
package com.pojo;
import java.io.Serializable;
import java.util.Date;
import java.util.Objects;
public class Emp implements Serializable {
private int empno;
private String ename;
private String job;
private int mgr;
private double sal;
private double comm;
private Date hiredate;
private Integer deptno;
public Emp() {
}
public Emp(int empno, String name, String job, int mgr, double sal, double comm, Date hiredate, Integer deptno) {
this.empno = empno;
this.ename = name;
this.job = job;
this.mgr = mgr;
this.sal = sal;
this.comm = comm;
this.hiredate = hiredate;
this.deptno = deptno;
}
public int getEmpno() {
return empno;
}
public void setEmpno(int empno) {
this.empno = empno;
}
public String getEname() {
return ename;
}
public void setEname(String name) {
this.ename = name;
}
public String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}
public int getMgr() {
return mgr;
}
public void setMgr(int mgr) {
this.mgr = mgr;
}
public double getSal() {
return sal;
}
public void setSal(double sal) {
this.sal = sal;
}
public double getComm() {
return comm;
}
public void setComm(double comm) {
this.comm = comm;
}
public Date getHiredate() {
return hiredate;
}
public void setHiredate(Date hiredate) {
this.hiredate = hiredate;
}
public Integer getDeptno() {
return deptno;
}
public void setDeptno(Integer deptno) {
this.deptno = deptno;
}
@Override
public String toString() {
return "Emp{" +
"empno=" + empno +
", name='" + ename + '\'' +
", job='" + job + '\'' +
", mgr=" + mgr +
", sal=" + sal +
", comm=" + comm +
", hiredate=" + hiredate +
", deptno=" + deptno +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Emp emp = (Emp) o;
return empno == emp.empno &&
mgr == emp.mgr &&
Double.compare(emp.sal, sal) == 0 &&
Double.compare(emp.comm, comm) == 0 &&
Objects.equals(ename, emp.ename) &&
Objects.equals(job, emp.job) &&
Objects.equals(hiredate, emp.hiredate) &&
Objects.equals(deptno, emp.deptno);
}
@Override
public int hashCode() {
return Objects.hash(empno, ename, job, mgr, sal, comm, hiredate, deptno);
}
}
EmpMapper接口代碼:
public interface EmpMapper {
/**
* @Description: 查詢所有的員工資料、查詢指定員工的資料
* @Param: [ename, deptno]
* @Return: java.util.List<com.pojo.Emp>
**/
List<Emp> queryAll(@Param("ename") String ename,@Param("deptno") Integer deptno);
/**
* @Description: 修改員工多個字段的資料
* @Param: [emp]
* @Return: int
**/
int updateEmp(Emp emp);
}
動态SQL:if
用于進行條件判斷, test 屬性用于指定判斷條件. 為了拼接條件, 在 SQL 語句後強行添加 1=1 的恒成立條件
<?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">
<!--命名空間,目前xml檔案所在位置-->
<mapper namespace="com.mappers.EmpMapper">
<!--if進行條件判斷,擷取對應的資料-->
<!--查詢所有的員工資料、查詢指定員工的資料,通過where 1=1 恒等式解決字元串拼接問題-->
<select id="queryAll" resultType="emp">
select * from emp where 1=1
<if test="ename!=null and ename!=''">
and ename = #{ename}
</if>
<if test="deptno!=null and deptno!=0">
and deptno = #{deptno}
</if>
</select>
</mapper>
測試類調用:
//1、加載會話
SqlSession session = SessionUtils.getSession();
//2、擷取EmpMapper執行個體對象
EmpMapper mapper = session.getMapper(EmpMapper.class);
//3、擷取資訊
List<Emp> emps = mapper.queryAll("", 0);
emps.forEach(System.out::println);
//4、關閉
session.close();
動态SQL:where
用于管理 where 子句. 有如下功能:
- 如果沒有條件, 不會生成 where 關鍵字
- 如果有條件, 會自動添加 where 關鍵字
- 如果第一個條件中有 and, 去除之
<?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">
<!--命名空間,目前xml檔案所在位置-->
<mapper namespace="com.mappers.EmpMapper">
<!--
用于管理 where 子句. 有如下功能:
1. 如果沒有條件, 不會生成 where 關鍵字
2. 如果有條件, 會自動添加 where 關鍵字
3. 如果第一個條件中有 and, 去除之
-->
<select id="queryAll" resultType="emp">
select * from emp
<where>
<if test="ename!=null and ename!=''">
and ename = #{ename}
</if>
<if test="deptno!=null and deptno!=0">
and deptno = #{deptno}
</if>
</where>
</select>
</mapper>
測試類調用:
//1、加載會話
SqlSession session = SessionUtils.getSession();
//2、擷取EmpMapper執行個體對象
EmpMapper mapper = session.getMapper(EmpMapper.class);
//3、擷取資訊,參數換了結果也會變,自己測試
List<Emp> emps = mapper.queryAll("", 0);
emps.forEach(System.out::println);
//4、關閉
session.close();
動态SQL:choose…when…otherwise
這是一整套标簽,類似于switch case…
<?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">
<!--命名空間,目前xml檔案所在位置-->
<mapper namespace="com.mappers.EmpMapper">
<!--choose标簽,類似于switch case,當滿足when标簽内部條件時,指派,ortherwise是不滿足when條件就加載它-->
<select id="queryAll" resultType="emp">
select * from emp
<where>
<choose>
<when test="ename!=null and ename!=''">
and ename = #{ename}
</when>
<when test="deptno!=null and deptno!=0">
and deptno = #{deptno}
</when>
<otherwise>and 1=1</otherwise>
</choose>
</where>
</select>
</mapper>
動态SQL:set
用于維護 update 語句中的 set 子句. 功能如下:
- 滿足條件時, 會自動添加 set 關鍵字
- 會去除 set 子句中多餘的逗号
- 不滿足條件時, 不會生成 set 關鍵字
在EmpMapper接口當中添加一個update方法
/**
* @Description: 修改員工多個字段的資料
* @Param: [emp]
* @Return: int
**/
int updateEmp(Emp emp);
EmpMapper.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">
<!--命名空間,目前xml檔案所在位置-->
<mapper namespace="com.mappers.EmpMapper">
<!--
用于維護 update 語句中的 set 子句. 功能如下:
1. 滿足條件時, 會自動添加 set 關鍵字
2. 會去除 set 子句中多餘的逗号
3. 不滿足條件時, 不會生成 set 關鍵字
-->
<update id="updateEmp" parameterType="emp">
update emp
<set>
empno = #{empno}
<if test="ename!=null and ename!=''">
ename = #{ename},
</if>
<if test="deptno!=null and deptno!=''">
deptno = #{deptno},
</if>
</set>
where empno = #{empno}
</update>
</mapper>
測試的話和之前的修改測試類一緻。
動态SQL:trim
用于在前後添加或删除一些内容
- prefix, 在前面添加内容
- prefixOverrides, 從前面去除内容
- su?ix, 向後面添加内容
- su?ixOverrides, 從後面去除内容
<?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">
<!--命名空間,目前xml檔案所在位置-->
<mapper namespace="com.mappers.EmpMapper">
<!--
使用trim代替where标簽
用于在前後添加或删除一些内容
1. prefix, 在前面添加内容
2. prefixOverrides, 從前面去除内容
3. suffix, 向後面添加内容
4. suffixOverrides, 從後面去除内容
-->
<select id="queryAll" resultType="emp">
select * from emp
<trim prefix="where" prefixOverrides="and">
<if test="ename!=null and ename!=''">
and ename = #{ename}
</if>
<if test="deptno!=null and deptno!=0">
and deptno = #{deptno}
</if>
</trim>
</select>
</mapper>
動态SQL:bind
用于對資料進行再加工, 用于模糊查詢
<?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">
<!--命名空間,目前xml檔案所在位置-->
<mapper namespace="com.mappers.EmpMapper">
<!--模糊比對-->
<select id="queryAll" resultType="emp">
select * from emp
<where>
<if test="ename!=null and ename!=''">
<bind name="ename" value="'%'+ename+'%'"/>
and ename like #{ename}
</if>
</where>
</select>
</mapper>
動态SQL:foreach
用于在 SQL 語句中周遊集合參數, 在 in 查詢中使用
- collection: 待周遊的集合
- open: 設定開始符号
- item: 疊代變量
- separator: 項目分隔符
- close: 設定結束符
這個在我的上一篇部落格中批量增删改資料那裡出現了很多次,這裡就不介紹了,有需要的自行前往:foreach使用
動态SQL:sql include
封裝一段SQL語句,實作代碼複用
<sql id="mySql"> id, username, password </sql>
<select id="selIn" parameterType="list" resultType="user">
select <include refid="mySql" /> from t_user where id in
<foreach collection="list" open="(" separator="," close=")" item="item">
#{item}
</foreach>
</select
動态SQL就介紹到這裡了,大家可以互相交流學習。
這裡就不介紹了,有需要的自行前往:foreach使用
動态SQL:sql include
封裝一段SQL語句,實作代碼複用
<sql id="mySql"> id, username, password </sql>
<select id="selIn" parameterType="list" resultType="user">
select <include refid="mySql" /> from t_user where id in
<foreach collection="list" open="(" separator="," close=")" item="item">
#{item}
</foreach>
</select
動态SQL就介紹到這裡了,大家可以互相交流學習。