前面我们介绍了Mybatis动态SQL的使用;本篇我们介绍使用mybatis-thymeleaf动态语言生成动态SQL。
如果您对Mybatis动态SQL不太了解,建议您先进行了解后再阅读本篇,可以参考:
Mybatis 动态SQL – 使用if,where标签动态生成条件语句
Mybatis 动态SQL – 使用if,set标签动态生成更新语句
Mybatis 动态SQL – 使用choose标签动态生成条件语句
Mybatis 动态SQL – 使用choose标签动态生成更新语句
Mybatis 动态SQL – 使用trim标签替代where,set标签
Mybatis 动态SQL - 使用foreach标签查询数据、批量新增、批量修改、删除数据
这里我们直接使用脚本初始化数据库中的数据
- -- 如果数据库不存在则创建数据库
- 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的教师表并向表中插入了数据
- <dependency>
- <groupId>org.mybatis.scriptinggroupId>
- <artifactId>mybatis-thymeleafartifactId>
- <version>1.0.4version>
- dependency>
在cn.horse.demo下创建TeacherInfo、TeacherInfoQuery实体类:
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 Integer getId() {
- return id;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- public String getName() {
- return name;
- }
-
- public void setDepartment(String department) {
- this.department = department;
- }
-
- public String getDepartment() {
- return department;
- }
-
- public void setBirth(LocalDate birth) {
- this.birth = birth;
- }
-
- public LocalDate getBirth() {
- return birth;
- }
-
- public void setDegree(String degree) {
- this.degree = degree;
- }
-
- public String getDegree() {
- return 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();
- }
- }
TeacherInfoQuery类:
- package cn.horse.demo;
-
- public class TeacherInfoQuery {
-
- private String department;
- private String degree;
-
- public void setDepartment(String department) {
- this.department = department;
- }
-
- public String getDepartment() {
- return department;
- }
-
- public void setDegree(String degree) {
- this.degree = degree;
- }
-
- public String getDegree() {
- return degree;
- }
- }
在resources的目录下新建TeacherInfoMapper.xml配置文件
- "1.0" encoding="UTF-8" ?>
- mapper
- PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
- "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
- <mapper namespace="cn.horse.demo.TeacherInfoMapper">
-
- mapper>
在resources下新建mybatis-config.xml配置文件,配置thymeleaf默认的脚本语言,并引入TeacherInfoMapper.xml配置文件
- "1.0" encoding="UTF-8" ?>
- 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"/>
- <setting name="defaultScriptingLanguage" value="org.mybatis.scripting.thymeleaf.ThymeleafLanguageDriver"/>
- 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>
其中
在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);
- }
- }
- }
在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();
- }
- }
- }
- 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");
- }
-
- private static void find(String statement, TeacherInfoQuery query) {
- SqlSession sqlSession = null;
- try {
- sqlSession = SqlSessionUtils.openSession();
- List
teacherInfoList = sqlSession.selectList(statement, query); - for (TeacherInfo teacherInfo: teacherInfoList) {
- System.out.println(teacherInfo);
- }
- } finally {
- SqlSessionUtils.closeSession(sqlSession);
- }
- }
-
- private static void insert(String statement, List
teacherInfoList) { - SqlSession sqlSession = null;
- try {
- sqlSession = SqlSessionUtils.openSession();
- sqlSession.insert(statement, teacherInfoList);
- sqlSession.commit();
- } finally {
- SqlSessionUtils.closeSession(sqlSession);
- }
- }
-
- private static void update(String statement, TeacherInfo teacherInfo) {
- SqlSession sqlSession = null;
- try {
- sqlSession = SqlSessionUtils.openSession();
- sqlSession.update(statement, teacherInfo);
- sqlSession.commit();
- } finally {
- SqlSessionUtils.closeSession(sqlSession);
- }
- }
-
- private static void delete(String statement, List
idList) { - SqlSession sqlSession = null;
- try {
- sqlSession = SqlSessionUtils.openSession();
- sqlSession.delete(statement, idList);
- sqlSession.commit();
- } finally {
- SqlSessionUtils.closeSession(sqlSession);
- }
- }
- }
在TeacherInfoMapper.xml配置文件中新增findByQuery查询语句:
- <select id="find" resultType="cn.horse.demo.TeacherInfo">
- SELECT
- ID,
- TEACHER_NAME name,
- DEPARTMENT,
- BIRTH,
- DEGREE
- FROM T_TEACHER
- WHERE 1 = 1
- /*[# th:if="${degree} != null and ${degree} != ''"]*/
- AND DEGREE = /*[# mb:p="degree"]*/ '' /*[/]*/
- /*[/]*/
- /*[# th:if="${department} != null and ${department} != ''"]*/
- AND DEPARTMENT = /*[# mb:p="department"]*/ '' /*[/]*/
- /*[/]*/
- select>
th:if类似于
测试:
- // 引入JDK日志配置
- System.setProperty("java.util.logging.config.class", "cn.horse.demo.JdkLogConfig");
-
- // 查询学历为本科的教师
- TeacherInfoQuery query = new TeacherInfoQuery();
- query.setDegree("BK");
- find("cn.horse.demo.TeacherInfoMapper.find", query);
执行后的结果如下:
在TeacherInfoMapper.xml配置文件中新增insert插入语句:
- <insert id="insert">
- INSERT INTO T_TEACHER(ID, TEACHER_NAME, DEPARTMENT, BIRTH, DEGREE)
- VALUES
- /*[# th:each="teacherInfo : ${list}"]*/
- (/*[# mb:p="teacherInfo.id"]*/ '' /*[/]*/,
- /*[# mb:p="teacherInfo.name"]*/ '' /*[/]*/,
- /*[# mb:p="teacherInfo.department"]*/ '' /*[/]*/,
- /*[# mb:p="teacherInfo.birth"]*/ '' /*[/]*/,
- /*[# mb:p="teacherInfo.degree"]*/ '' /*[/]*/)
- /*[(${teacherInfoStat.last} ? '' : ',')]*/
- /*[/]*/
- insert>
测试:
- // 引入JDK日志配置
- System.setProperty("java.util.logging.config.class", "cn.horse.demo.JdkLogConfig");
-
- List
teacherInfoList = new ArrayList<>(); - TeacherInfo teacherInfo1 = new TeacherInfo();
- teacherInfo1.setId(11);
- teacherInfo1.setName("张三11");
- teacherInfo1.setDepartment("001");
- teacherInfo1.setBirth(LocalDate.of(1988, 5, 20));
- teacherInfo1.setDegree("BK");
- teacherInfoList.add(teacherInfo1);
-
- TeacherInfo teacherInfo2 = new TeacherInfo();
- teacherInfo2.setId(12);
- teacherInfo2.setName("李四12");
- teacherInfo2.setDepartment("003");
- teacherInfo2.setBirth(LocalDate.of(1989, 8, 10));
- teacherInfo2.setDegree("ZK");
- teacherInfoList.add(teacherInfo2);
- insert("cn.horse.demo.TeacherInfoMapper.insert", teacherInfoList);
执行的结果如下:
在TeacherInfoMapper.xml配置文件中新增update更新语句:
- <update id="update">
- UPDATE T_TEACHER
- SET
-
- ID = /*[# mb:p="id"]*/ '' /*[/]*/
- /*[# th:if="${name} != null and ${name} != ''"]*/
- , TEACHER_NAME = /*[# mb:p="name"]*/ '' /*[/]*/
- /*[/]*/
- /*[# th:if="${department} != null and ${department} != ''"]*/
- , DEPARTMENT = /*[# mb:p="department"]*/ '' /*[/]*/
- /*[/]*/
- /*[# th:if="${birth} != null"]*/
- , BIRTH = /*[# mb:p="birth"]*/ '' /*[/]*/
- /*[/]*/
- /*[# th:if="${degree} != null and ${degree} != ''"]*/
- , DEGREE = /*[# mb:p="degree"]*/ '' /*[/]*/
- /*[/]*/
- ]]>
- WHERE ID = /*[# mb:p="id"]*/ '' /*[/]*/
- update>
测试:
- // 引入JDK日志配置
- System.setProperty("java.util.logging.config.class", "cn.horse.demo.JdkLogConfig");
-
- TeacherInfo teacherInfo = new TeacherInfo();
- teacherInfo.setId(11);
- teacherInfo.setName("张三22");
- update("cn.horse.demo.TeacherInfoMapper.update", teacherInfo);
执行的结果如下:
六、批量删除数据
在TeacherInfoMapper.xml配置文件中新增delete删除语句:
- <delete id="delete">
- DELETE FROM T_TEACHER
- WHERE ID IN (
- /*[# th:each="id : ${list}"]*/
- /*[# mb:p="id"]*/ '' /*[/]*/
- /*[(${idStat.last} ? '' : ',')]*/
- /*[/]*/
- )
- delete>
测试:
- // 引入JDK日志配置
- System.setProperty("java.util.logging.config.class", "cn.horse.demo.JdkLogConfig");
-
- delete("cn.horse.demo.TeacherInfoMapper.delete", Arrays.asList(11, 12));
执行的结果如下: