前面几篇我们介绍了where,set标签的使用;本篇我们继续介绍如何使用Mybatis提供的tirm标签替代where,set标签。
如果您对where,set标签不太了解,建议您先进行了解后再阅读本篇,可以参考:
Mybatis 动态SQL – 使用if,where标签动态生成条件语句
Mybatis 动态SQL – 使用if,set标签动态生成更新语句
一、数据准备
这里我们直接使用脚本初始化数据库中的数据
-- 如果数据库不存在则创建数据库
CREATE DATABASE IF NOT EXISTS demo DEFAULT CHARSET utf8;
-- 切换数据库
USE demo;
-- 创建用户表
CREATE TABLE IF NOT EXISTS T_TEACHER(
ID INT PRIMARY KEY COMMENT '教师编号',
TEACHER_NAME VARCHAR(64) NOT NULL COMMENT '教师名称',
DEPARTMENT VARCHAR(16) NOT NULL COMMENT '所属部门',
BIRTH DATE NOT NULL COMMENT '出生年月',
DEGREE VARCHAR(16) NOT NULL COMMENT '学历(ZK:专科, BK:本科, YJS:研究生, BS:博士)'
);
-- 插入用户数据
INSERT INTO T_TEACHER(ID, TEACHER_NAME, DEPARTMENT, BIRTH, DEGREE)
VALUES(1, '张三1', '001', '1990-06-12', 'BK'),
(2, '李四1', '002', '1992-05-10', 'BK'),
(3, '张三2', '003', '1988-01-15', 'YJS'),
(4, '李四2', '001', '1979-03-10', 'BK'),
(5, '李四3', '003', '1995-08-16', 'YJS');
创建了一个名称为demo的数据库;并在库里创建了名称为T_TEACHER的教师表并向表中插入了数据
二、环境搭建
1、创建实体类
在cn.horse.demo下创建TeacherInfo实体类:
TeacherInfo类:
package cn.horse.demo;
import java.time.LocalDate;
public class TeacherInfo {
private Integer id;
private String name;
private String department;
private LocalDate birth;
private String degree;
public void setId(Integer id) {
this.id = id;
}
public void setDepartment(String department) {
this.department = department;
}
public void setDegree(String degree) {
this.degree = degree;
}
@Override
public String toString() {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("{ ");
stringBuilder.append("id: ");
stringBuilder.append(this.id);
stringBuilder.append(", ");
stringBuilder.append("name: ");
stringBuilder.append(this.name);
stringBuilder.append(", ");
stringBuilder.append("department: ");
stringBuilder.append(this.department);
stringBuilder.append(", ");
stringBuilder.append("birth: ");
stringBuilder.append(this.birth);
stringBuilder.append(", ");
stringBuilder.append("degree: ");
stringBuilder.append(this.degree);
stringBuilder.append(" }");
return stringBuilder.toString();
}
}
2、Mapper配置文件
在resources的目录下新建TeacherInfoMapper.xml配置文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.horse.demo.TeacherInfoMapper">
<select id="findById" resultType="cn.horse.demo.TeacherInfo">
SELECT
ID,
TEACHER_NAME name,
DEPARTMENT,
BIRTH,
DEGREE
FROM T_TEACHER
WHERE ID = #{id}
</select>
<select id="findByQuery" parameterType="cn.horse.demo.TeacherInfoQuery" resultType="cn.horse.demo.TeacherInfo">
SELECT
ID,
TEACHER_NAME name,
DEPARTMENT,
BIRTH,
DEGREE
FROM T_TEACHER
<where>
<if test="null != degree and '' != degree">
AND DEGREE = #{degree}
</if>
<if test="null != department and '' != department">
AND DEPARTMENT = #{department}
</if>
</where>
</select>
<update id="updateByEntity" parameterType="cn.horse.demo.TeacherInfo">
UPDATE T_TEACHER
<set>
<if test="null != department and '' != department">
DEPARTMENT = #{department},
</if>
<if test="null != degree and '' != degree">
DEGREE = #{degree},
</if>
</set>
WHERE ID = #{id}
</update>
</mapper>
3、引入配置文件
在resources下新建mybatis-config.xml配置文件,并引入TeacherInfoMapper.xml配置文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
<setting name="logImpl" value="JDK_LOGGING"/>
</settings>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="org.gjt.mm.mysql.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/demo?useUnicode=true&useSSL=false&characterEncoding=utf8"/>
<property name="username" value="root"/>
<property name="password" value="horse"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="demo/TeacherInfoMapper.xml" />
</mappers>
</configuration>
4、会话工具类
在cn.horse.demo包下新建SqlSessionUtils工具类
package cn.horse.demo;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.InputStream;
import java.util.Objects;
public class SqlSessionUtils {
private static final SqlSessionFactory sqlSessionFactory;
static {
// 读取mybatis配置文件
InputStream inputStream = ClassLoader.getSystemClassLoader().getResourceAsStream("mybatis-config.xml");
// 根据配置创建SqlSession工厂
sqlSessionFactory = new SqlSessionFactoryBuilder()
.build(inputStream);
}
/**
* 开启会话
* @return
*/
public static SqlSession openSession() {
return sqlSessionFactory.openSession();
}
/**
* 关闭会话
* @param sqlSession
*/
public static void closeSession(SqlSession sqlSession) {
if(Objects.nonNull(sqlSession)) {
sqlSession.close();
}
}
}
5、JDK 日志系统配置
在resources的目录下新建logging.properties配置文件
handlers=java.util.logging.ConsoleHandler
.level=INFO
cn.horse.demo.TeacherInfoMapper.level=FINER
java.util.logging.ConsoleHandler.level=ALL
java.util.logging.ConsoleHandler.formatter=java.util.logging.SimpleFormatter
java.util.logging.SimpleFormatter.format=%1$tY-%1$tm-%1$td %1$tT.%1$tL %4$s %3$s - %5$s%6$s%n
在cn.horse.demo下新建JdkLogConfig类:
JdkLogConfig类:
package cn.horse.demo;
import java.io.IOException;
import java.io.InputStream;
import java.util.logging.LogManager;
public class JdkLogConfig {
public JdkLogConfig() {
try {
InputStream inputStream = ClassLoader.getSystemClassLoader().getResourceAsStream("logging.properties");
LogManager.getLogManager().readConfiguration(inputStream);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
6、启动程序
package cn.horse.demo;
import org.apache.ibatis.session.SqlSession;
import java.util.List;
public class Main {
public static void main(String[] args) {
// 引入JDK日志配置
System.setProperty("java.util.logging.config.class", "cn.horse.demo.JdkLogConfig");
// 查询学历为本科的教师
TeacherInfoQuery query = new TeacherInfoQuery();
query.setDegree("BK");
findAll("cn.horse.demo.TeacherInfoMapper.findByQuery", query);
// 更新编号为2的教师
TeacherInfo teacherInfo = new TeacherInfo();
teacherInfo.setId(2);
teacherInfo.setDegree("BK");
updateByEntity("cn.horse.demo.TeacherInfoMapper.updateByEntity", teacherInfo);
// 查询编号为2的教师
findById("cn.horse.demo.TeacherInfoMapper.findById", 2);
}
private static void findAll(String statement, TeacherInfoQuery query) {
SqlSession sqlSession = null;
try {
sqlSession = SqlSessionUtils.openSession();
List<TeacherInfo> teacherInfoList = sqlSession.selectList(statement, query);
for (TeacherInfo teacherInfo: teacherInfoList) {
System.out.println(teacherInfo);
}
} finally {
SqlSessionUtils.closeSession(sqlSession);
}
}
private static void updateByEntity(String statement, TeacherInfo teacherInfo) {
SqlSession sqlSession = null;
try {
sqlSession = SqlSessionUtils.openSession();
sqlSession.update(statement, teacherInfo);
sqlSession.commit();
} finally {
SqlSessionUtils.closeSession(sqlSession);
}
}
private static void findById(String statement, Integer id) {
SqlSession sqlSession = null;
try {
sqlSession = SqlSessionUtils.openSession();
TeacherInfo teacherInfo = sqlSession.selectOne(statement, id);
System.out.println(teacherInfo);
} finally {
SqlSessionUtils.closeSession(sqlSession);
}
}
}
执行后的结果如下:
三、trim标签替代where标签
之前我们介绍过where标签的两个作用:
(1)判断是否存在条件,如果条件不存在,则不再拼接where;如果条件存在,则拼接where
(2)剔除where后面多余的AND或OR
下面我们给出where等效的trim标签配置:
<trim prefix="where" prefixOverrides="AND | OR">
</trim>
prefix属性:当trim标签中内容不为空时,则拼接prefix的属性值
prefixOverrides属性:当trim标签中的内容以AND或OR开头时,则剔除AND或OR
下面我们修改TeacherInfoMapper.xml配置文件中的findByQuery查询语句:
<select id="findByQuery" parameterType="cn.horse.demo.TeacherInfoQuery" resultType="cn.horse.demo.TeacherInfo">
SELECT
ID,
TEACHER_NAME name,
DEPARTMENT,
BIRTH,
DEGREE
FROM T_TEACHER
<trim prefix="where" prefixOverrides="AND | OR">
<if test="null != degree and '' != degree">
AND DEGREE = #{degree}
</if>
<if test="null != department and '' != department">
AND DEPARTMENT = #{department}
</if>
</trim>
</select>
测试:
// 引入JDK日志配置
System.setProperty("java.util.logging.config.class", "cn.horse.demo.JdkLogConfig");
// 查询学历为研究生的教师
TeacherInfoQuery query = new TeacherInfoQuery();
query.setDegree("YJS");
findAll("cn.horse.demo.TeacherInfoMapper.findByQuery", query);
执行后的结果如下:
四、trim标签替代set标签
之前我们介绍过set标签可用于剔除更新语句中多余的逗号
下面我们给出set等效的trim标签配置:
<trim prefix="set" suffixOverrides=",">
</trim>
prefix属性:当trim标签中内容不为空时,则拼接prefix的属性值
suffixOverrides属性:当trim标签中的内容以逗号结束时,则剔除逗号
下面我们修改TeacherInfoMapper.xml配置文件中的updateByEntity查询语句:
<update id="updateByEntity" parameterType="cn.horse.demo.TeacherInfo">
UPDATE T_TEACHER
<trim prefix="set" suffixOverrides=",">
<if test="null != department and '' != department">
DEPARTMENT = #{department},
</if>
<if test="null != degree and '' != degree">
DEGREE = #{degree},
</if>
</trim>
WHERE ID = #{id}
</update>
测试:
// 引入JDK日志配置
System.setProperty("java.util.logging.config.class", "cn.horse.demo.JdkLogConfig");
// 更新编号为2的教师
TeacherInfo teacherInfo = new TeacherInfo();
teacherInfo.setId(2);
teacherInfo.setDegree("BK");
updateByEntity("cn.horse.demo.TeacherInfoMapper.updateByEntity", teacherInfo);
// 查询编号为2的教师
findById("cn.horse.demo.TeacherInfoMapper.findById", 2);
查询的结果如下: