• Mybatis 动态语言 - mybatis-thymeleaf


    前面我们介绍了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标签查询数据、批量新增、批量修改、删除数据

    一、数据准备

    这里我们直接使用脚本初始化数据库中的数据

    1. -- 如果数据库不存在则创建数据库
    2. CREATE DATABASE IF NOT EXISTS demo DEFAULT CHARSET utf8;
    3. -- 切换数据库
    4. USE demo;
    5. -- 创建用户表
    6. CREATE TABLE IF NOT EXISTS T_TEACHER(
    7. ID INT PRIMARY KEY COMMENT '教师编号',
    8. TEACHER_NAME VARCHAR(64) NOT NULL COMMENT '教师名称',
    9. DEPARTMENT VARCHAR(16) NOT NULL COMMENT '所属部门',
    10. BIRTH DATE NOT NULL COMMENT '出生年月',
    11. DEGREE VARCHAR(16) NOT NULL COMMENT '学历(ZK:专科, BK:本科, YJS:研究生, BS:博士)'
    12. );
    13. -- 插入用户数据
    14. INSERT INTO T_TEACHER(ID, TEACHER_NAME, DEPARTMENT, BIRTH, DEGREE)
    15. VALUES(1, '张三1', '001', '1990-06-12', 'BK'),
    16. (2, '李四1', '002', '1992-05-10', 'BK'),
    17. (3, '张三2', '003', '1988-01-15', 'YJS'),
    18. (4, '李四2', '001', '1979-03-10', 'BK'),
    19. (5, '李四3', '003', '1995-08-16', 'YJS');

    创建了一个名称为demo的数据库;并在库里创建了名称为T_TEACHER的教师表并向表中插入了数据

    二、环境准备

    1、添加依赖

    1. <dependency>
    2. <groupId>org.mybatis.scriptinggroupId>
    3. <artifactId>mybatis-thymeleafartifactId>
    4. <version>1.0.4version>
    5. dependency>

    2、创建实体类

    在cn.horse.demo下创建TeacherInfo、TeacherInfoQuery实体类:

    TeacherInfo类:

    1. package cn.horse.demo;
    2. import java.time.LocalDate;
    3. public class TeacherInfo {
    4. private Integer id;
    5. private String name;
    6. private String department;
    7. private LocalDate birth;
    8. private String degree;
    9. public void setId(Integer id) {
    10. this.id = id;
    11. }
    12. public Integer getId() {
    13. return id;
    14. }
    15. public void setName(String name) {
    16. this.name = name;
    17. }
    18. public String getName() {
    19. return name;
    20. }
    21. public void setDepartment(String department) {
    22. this.department = department;
    23. }
    24. public String getDepartment() {
    25. return department;
    26. }
    27. public void setBirth(LocalDate birth) {
    28. this.birth = birth;
    29. }
    30. public LocalDate getBirth() {
    31. return birth;
    32. }
    33. public void setDegree(String degree) {
    34. this.degree = degree;
    35. }
    36. public String getDegree() {
    37. return degree;
    38. }
    39. @Override
    40. public String toString() {
    41. StringBuilder stringBuilder = new StringBuilder();
    42. stringBuilder.append("{ ");
    43. stringBuilder.append("id: ");
    44. stringBuilder.append(this.id);
    45. stringBuilder.append(", ");
    46. stringBuilder.append("name: ");
    47. stringBuilder.append(this.name);
    48. stringBuilder.append(", ");
    49. stringBuilder.append("department: ");
    50. stringBuilder.append(this.department);
    51. stringBuilder.append(", ");
    52. stringBuilder.append("birth: ");
    53. stringBuilder.append(this.birth);
    54. stringBuilder.append(", ");
    55. stringBuilder.append("degree: ");
    56. stringBuilder.append(this.degree);
    57. stringBuilder.append(" }");
    58. return stringBuilder.toString();
    59. }
    60. }

    TeacherInfoQuery类:

    1. package cn.horse.demo;
    2. public class TeacherInfoQuery {
    3. private String department;
    4. private String degree;
    5. public void setDepartment(String department) {
    6. this.department = department;
    7. }
    8. public String getDepartment() {
    9. return department;
    10. }
    11. public void setDegree(String degree) {
    12. this.degree = degree;
    13. }
    14. public String getDegree() {
    15. return degree;
    16. }
    17. }

    3、Mapper配置文件

    在resources的目录下新建TeacherInfoMapper.xml配置文件

    1. "1.0" encoding="UTF-8" ?>
    2. mapper
    3. PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
    4. "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
    5. <mapper namespace="cn.horse.demo.TeacherInfoMapper">
    6. mapper>

    4、动态语言配置

    在resources下新建mybatis-config.xml配置文件,配置thymeleaf默认的脚本语言,并引入TeacherInfoMapper.xml配置文件

    1. "1.0" encoding="UTF-8" ?>
    2. configuration
    3. PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
    4. "http://mybatis.org/dtd/mybatis-3-config.dtd">
    5. <configuration>
    6. <settings>
    7. <setting name="logImpl" value="JDK_LOGGING"/>
    8. <setting name="defaultScriptingLanguage" value="org.mybatis.scripting.thymeleaf.ThymeleafLanguageDriver"/>
    9. settings>
    10. <environments default="development">
    11. <environment id="development">
    12. <transactionManager type="JDBC"/>
    13. <dataSource type="POOLED">
    14. <property name="driver" value="org.gjt.mm.mysql.Driver"/>
    15. <property name="url" value="jdbc:mysql://localhost:3306/demo?useUnicode=true&useSSL=false&characterEncoding=utf8"/>
    16. <property name="username" value="root"/>
    17. <property name="password" value="horse"/>
    18. dataSource>
    19. environment>
    20. environments>
    21. <mappers>
    22. <mapper resource="demo/TeacherInfoMapper.xml" />
    23. mappers>
    24. configuration>

    其中用于配置thymeleaf作为默认的动态语言

    5、日志配置

    在resources的目录下新建logging.properties配置文件

    1. handlers=java.util.logging.ConsoleHandler
    2. .level=INFO
    3. cn.horse.demo.TeacherInfoMapper.level=FINER
    4. java.util.logging.ConsoleHandler.level=ALL
    5. java.util.logging.ConsoleHandler.formatter=java.util.logging.SimpleFormatter
    6. 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类:

    1. package cn.horse.demo;
    2. import java.io.IOException;
    3. import java.io.InputStream;
    4. import java.util.logging.LogManager;
    5. public class JdkLogConfig {
    6. public JdkLogConfig() {
    7. try {
    8. InputStream inputStream = ClassLoader.getSystemClassLoader().getResourceAsStream("logging.properties");
    9. LogManager.getLogManager().readConfiguration(inputStream);
    10. } catch (IOException e) {
    11. throw new RuntimeException(e);
    12. }
    13. }
    14. }

    6、会话工具类

    在cn.horse.demo包下新建SqlSessionUtils工具类

    1. package cn.horse.demo;
    2. import org.apache.ibatis.session.SqlSession;
    3. import org.apache.ibatis.session.SqlSessionFactory;
    4. import org.apache.ibatis.session.SqlSessionFactoryBuilder;
    5. import java.io.InputStream;
    6. import java.util.Objects;
    7. public class SqlSessionUtils {
    8. private static final SqlSessionFactory sqlSessionFactory;
    9. static {
    10. // 读取mybatis配置文件
    11. InputStream inputStream = ClassLoader.getSystemClassLoader().getResourceAsStream("mybatis-config.xml");
    12. // 根据配置创建SqlSession工厂
    13. sqlSessionFactory = new SqlSessionFactoryBuilder()
    14. .build(inputStream);
    15. }
    16. /**
    17. * 开启会话
    18. * @return
    19. */
    20. public static SqlSession openSession() {
    21. return sqlSessionFactory.openSession();
    22. }
    23. /**
    24. * 关闭会话
    25. * @param sqlSession
    26. */
    27. public static void closeSession(SqlSession sqlSession) {
    28. if(Objects.nonNull(sqlSession)) {
    29. sqlSession.close();
    30. }
    31. }
    32. }

    7、启动程序配置

    1. package cn.horse.demo;
    2. import org.apache.ibatis.session.SqlSession;
    3. import java.util.List;
    4. public class Main {
    5. public static void main(String[] args) {
    6. // 引入JDK日志配置
    7. System.setProperty("java.util.logging.config.class", "cn.horse.demo.JdkLogConfig");
    8. }
    9. private static void find(String statement, TeacherInfoQuery query) {
    10. SqlSession sqlSession = null;
    11. try {
    12. sqlSession = SqlSessionUtils.openSession();
    13. List teacherInfoList = sqlSession.selectList(statement, query);
    14. for (TeacherInfo teacherInfo: teacherInfoList) {
    15. System.out.println(teacherInfo);
    16. }
    17. } finally {
    18. SqlSessionUtils.closeSession(sqlSession);
    19. }
    20. }
    21. private static void insert(String statement, List teacherInfoList) {
    22. SqlSession sqlSession = null;
    23. try {
    24. sqlSession = SqlSessionUtils.openSession();
    25. sqlSession.insert(statement, teacherInfoList);
    26. sqlSession.commit();
    27. } finally {
    28. SqlSessionUtils.closeSession(sqlSession);
    29. }
    30. }
    31. private static void update(String statement, TeacherInfo teacherInfo) {
    32. SqlSession sqlSession = null;
    33. try {
    34. sqlSession = SqlSessionUtils.openSession();
    35. sqlSession.update(statement, teacherInfo);
    36. sqlSession.commit();
    37. } finally {
    38. SqlSessionUtils.closeSession(sqlSession);
    39. }
    40. }
    41. private static void delete(String statement, List idList) {
    42. SqlSession sqlSession = null;
    43. try {
    44. sqlSession = SqlSessionUtils.openSession();
    45. sqlSession.delete(statement, idList);
    46. sqlSession.commit();
    47. } finally {
    48. SqlSessionUtils.closeSession(sqlSession);
    49. }
    50. }
    51. }

    三、查询数据

    在TeacherInfoMapper.xml配置文件中新增findByQuery查询语句:

    1. <select id="find" resultType="cn.horse.demo.TeacherInfo">
    2. SELECT
    3. ID,
    4. TEACHER_NAME name,
    5. DEPARTMENT,
    6. BIRTH,
    7. DEGREE
    8. FROM T_TEACHER
    9. WHERE 1 = 1
    10. /*[# th:if="${degree} != null and ${degree} != ''"]*/
    11. AND DEGREE = /*[# mb:p="degree"]*/ '' /*[/]*/
    12. /*[/]*/
    13. /*[# th:if="${department} != null and ${department} != ''"]*/
    14. AND DEPARTMENT = /*[# mb:p="department"]*/ '' /*[/]*/
    15. /*[/]*/
    16. select>

    th:if类似于标签,第一个标签代表的是degree不为null并且不为空字符串,第二个标签代表的是department不为null并且不为空字符串;

    测试:

    1. // 引入JDK日志配置
    2. System.setProperty("java.util.logging.config.class", "cn.horse.demo.JdkLogConfig");
    3. // 查询学历为本科的教师
    4. TeacherInfoQuery query = new TeacherInfoQuery();
    5. query.setDegree("BK");
    6. find("cn.horse.demo.TeacherInfoMapper.find", query);

    执行后的结果如下:

    四、批量插入数据

    在TeacherInfoMapper.xml配置文件中新增insert插入语句:

    1. <insert id="insert">
    2. INSERT INTO T_TEACHER(ID, TEACHER_NAME, DEPARTMENT, BIRTH, DEGREE)
    3. VALUES
    4. /*[# th:each="teacherInfo : ${list}"]*/
    5. (/*[# mb:p="teacherInfo.id"]*/ '' /*[/]*/,
    6. /*[# mb:p="teacherInfo.name"]*/ '' /*[/]*/,
    7. /*[# mb:p="teacherInfo.department"]*/ '' /*[/]*/,
    8. /*[# mb:p="teacherInfo.birth"]*/ '' /*[/]*/,
    9. /*[# mb:p="teacherInfo.degree"]*/ '' /*[/]*/)
    10. /*[(${teacherInfoStat.last} ? '' : ',')]*/
    11. /*[/]*/
    12. insert>

    测试:

    1. // 引入JDK日志配置
    2. System.setProperty("java.util.logging.config.class", "cn.horse.demo.JdkLogConfig");
    3. List teacherInfoList = new ArrayList<>();
    4. TeacherInfo teacherInfo1 = new TeacherInfo();
    5. teacherInfo1.setId(11);
    6. teacherInfo1.setName("张三11");
    7. teacherInfo1.setDepartment("001");
    8. teacherInfo1.setBirth(LocalDate.of(1988, 5, 20));
    9. teacherInfo1.setDegree("BK");
    10. teacherInfoList.add(teacherInfo1);
    11. TeacherInfo teacherInfo2 = new TeacherInfo();
    12. teacherInfo2.setId(12);
    13. teacherInfo2.setName("李四12");
    14. teacherInfo2.setDepartment("003");
    15. teacherInfo2.setBirth(LocalDate.of(1989, 8, 10));
    16. teacherInfo2.setDegree("ZK");
    17. teacherInfoList.add(teacherInfo2);
    18. insert("cn.horse.demo.TeacherInfoMapper.insert", teacherInfoList);

    执行的结果如下:

    五、更新数据

    在TeacherInfoMapper.xml配置文件中新增update更新语句:

    1. <update id="update">
    2. UPDATE T_TEACHER
    3. SET
    4. ID = /*[# mb:p="id"]*/ '' /*[/]*/
    5. /*[# th:if="${name} != null and ${name} != ''"]*/
    6. , TEACHER_NAME = /*[# mb:p="name"]*/ '' /*[/]*/
    7. /*[/]*/
    8. /*[# th:if="${department} != null and ${department} != ''"]*/
    9. , DEPARTMENT = /*[# mb:p="department"]*/ '' /*[/]*/
    10. /*[/]*/
    11. /*[# th:if="${birth} != null"]*/
    12. , BIRTH = /*[# mb:p="birth"]*/ '' /*[/]*/
    13. /*[/]*/
    14. /*[# th:if="${degree} != null and ${degree} != ''"]*/
    15. , DEGREE = /*[# mb:p="degree"]*/ '' /*[/]*/
    16. /*[/]*/
    17. ]]>
    18. WHERE ID = /*[# mb:p="id"]*/ '' /*[/]*/
    19. update>

    测试:

    1. // 引入JDK日志配置
    2. System.setProperty("java.util.logging.config.class", "cn.horse.demo.JdkLogConfig");
    3. TeacherInfo teacherInfo = new TeacherInfo();
    4. teacherInfo.setId(11);
    5. teacherInfo.setName("张三22");
    6. update("cn.horse.demo.TeacherInfoMapper.update", teacherInfo);

    执行的结果如下:

    六、批量删除数据

    在TeacherInfoMapper.xml配置文件中新增delete删除语句:

    1. <delete id="delete">
    2. DELETE FROM T_TEACHER
    3. WHERE ID IN (
    4. /*[# th:each="id : ${list}"]*/
    5. /*[# mb:p="id"]*/ '' /*[/]*/
    6. /*[(${idStat.last} ? '' : ',')]*/
    7. /*[/]*/
    8. )
    9. delete>

    测试:

    1. // 引入JDK日志配置
    2. System.setProperty("java.util.logging.config.class", "cn.horse.demo.JdkLogConfig");
    3. delete("cn.horse.demo.TeacherInfoMapper.delete", Arrays.asList(11, 12));

    执行的结果如下:

  • 相关阅读:
    云原生架构案例分析_3.某快递公司核心业务系统云原生改造
    写给学生的一点建议-如何构建自己的知识体系?
    c语言,c++,JAVA,Python应该怎么选择?
    milvus数据库-连接
    【PAT甲级】1073 Scientific Notation
    IC Nansha|AMD高级副总裁、大中华区总裁潘晓明:制程、架构、平台优化突破计算边界
    GO sync.Map Store、Delete 、Load 、Range等方法使用举例
    千益畅行,旅游卡真相,成本与赋能潜力
    软件测试肖sir__python之ui自动化测试框架作业案例
    【阅读论文】-- IDmvis:面向1型糖尿病治疗决策支持的时序事件序列可视化
  • 原文地址:https://blog.csdn.net/m1729339749/article/details/132831016