食之无味,弃之可惜。

第一章:SQL 构建对象介绍

  • 之前通过注解开发的时候,相关的 SQL 语句都是自己直接拼接的,但是一些关键字写起来比较麻烦,而且容易出错。
  • Mybatis 给我们提供了 org.apache.ibatis.jdbc.SQL 功能类,专门用于构建 SQL 。 | 方法名 | 说明 | | —- | —- | | SELECT(String…column) | 根据字段拼接查询语句 | | FROM(String…table) | 根据表名拼接语句 | | WHERE(String…condition) | 根据条件拼接语句 | | INSERT_INTO(String table) | 根据表名拼接新增语句 | | VALUES(String column,String values) | 根据字段和值拼接插入数据语句 | | UPDATE(String table) | 根据表名拼接修改语句 | | DELETE_FROM(String table) | 根据表名拼接删除语句 | | …… | …… |

第二章:准备工作

2.1 开发环境

  • JDK 1.8+。
  • IDEA 2021+。
  • MySQL 5.7。
  • Gradle 6.5+。

2.2 SQL 脚本

  1. DROP TABLE IF EXISTS `student`;
  2. CREATE TABLE `student` (
  3. `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键',
  4. `name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '学生姓名',
  5. `age` int(11) NULL DEFAULT NULL COMMENT '学生年龄',
  6. PRIMARY KEY (`id`) USING BTREE
  7. ) ENGINE = InnoDB AUTO_INCREMENT = 3 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;
  8. INSERT INTO `student` VALUES (1, '张三', 20);
  9. INSERT INTO `student` VALUES (2, '李四', 25);

2.3 环境搭建

  • build.gradle
  1. plugins {
  2. id 'war'
  3. id 'java'
  4. }
  5. group 'org.example'
  6. version '1.0'
  7. repositories {
  8. mavenLocal()
  9. mavenCentral()
  10. }
  11. dependencies {
  12. /* Junit单元测试 */
  13. testImplementation 'junit:junit:4.13.2'
  14. /* Mybatis */
  15. implementation 'org.mybatis:mybatis:3.5.7'
  16. /* MySQL */
  17. implementation 'mysql:mysql-connector-java:8.0.26'
  18. /* 数据源 */
  19. implementation 'com.alibaba:druid:1.2.8'
  20. /* 日志 */
  21. implementation 'log4j:log4j:1.2.17'
  22. }
  • log4j.xml
  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
  3. <log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
  4. <appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
  5. <param name="Encoding" value="UTF-8"/>
  6. <layout class="org.apache.log4j.PatternLayout">
  7. <param name="ConversionPattern" value="%-5p %d{MM-dd HH:mm:ss,SSS} %m (%F:%L) \n"/>
  8. </layout>
  9. </appender>
  10. <logger name="java.sql">
  11. <level value="debug"/>
  12. </logger>
  13. <logger name="org.apache.ibatis">
  14. <level value="info"/>
  15. </logger>
  16. <root>
  17. <level value="debug"/>
  18. <appender-ref ref="STDOUT"/>
  19. </root>
  20. </log4j:configuration>
  • mybatis-config.xml
  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE configuration
  3. PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  4. "http://mybatis.org/dtd/mybatis-3-config.dtd">
  5. <configuration>
  6. <!-- environments表示配置Mybatis的开发环境,可以配置多个环境,在众多具体环境中,使用default属性指定实际运行时使用的环境。default属性的取值是environment标签的id属性的值。 -->
  7. <environments default="development">
  8. <!-- environment表示配置Mybatis的一个具体的环境 -->
  9. <environment id="development">
  10. <!-- Mybatis的内置的事务管理器 -->
  11. <transactionManager type="JDBC"/>
  12. <!-- 配置数据源 -->
  13. <dataSource type="POOLED">
  14. <!-- 建立数据库连接的具体信息 -->
  15. <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
  16. <property name="url" value="jdbc:mysql://localhost:3306/test"/>
  17. <property name="username" value="root"/>
  18. <property name="password" value="123456"/>
  19. </dataSource>
  20. </environment>
  21. </environments>
  22. <mappers>
  23. <package name="com.github.mapper"/>
  24. </mappers>
  25. </configuration>
  • Student.java
  1. package com.github.entity;
  2. import java.io.Serializable;
  3. /**
  4. * @author 许大仙
  5. * @version 1.0
  6. * @since 2021-11-02 11:06
  7. */
  8. public class Student implements Serializable {
  9. private Integer id;
  10. private String name;
  11. private Integer age;
  12. public Integer getId() {
  13. return id;
  14. }
  15. public void setId(Integer id) {
  16. this.id = id;
  17. }
  18. public String getName() {
  19. return name;
  20. }
  21. public void setName(String name) {
  22. this.name = name;
  23. }
  24. public Integer getAge() {
  25. return age;
  26. }
  27. public void setAge(Integer age) {
  28. this.age = age;
  29. }
  30. @Override
  31. public String toString() {
  32. return "Student{" + "id=" + id + ", name='" + name + '\'' + ", age=" + age + '}';
  33. }
  34. }

第三章:使用 SQL 功能类构建 SQL 语句

  • 示例:
  1. package com.github.mybatis;
  2. import org.apache.ibatis.io.Resources;
  3. import org.apache.ibatis.jdbc.SQL;
  4. import org.apache.ibatis.session.SqlSession;
  5. import org.apache.ibatis.session.SqlSessionFactory;
  6. import org.apache.ibatis.session.SqlSessionFactoryBuilder;
  7. import org.junit.After;
  8. import org.junit.Before;
  9. import org.junit.Test;
  10. import java.io.IOException;
  11. import java.io.InputStream;
  12. /**
  13. * @author 许大仙
  14. * @version 1.0
  15. * @since 2021-10-29 14:19
  16. */
  17. public class MybatisTest {
  18. SqlSession sqlSession;
  19. @Before
  20. public void before() throws IOException {
  21. // 使用Mybatis的Resources读取mybatis-config.xml配置文件
  22. InputStream resourceAsStream = Resources.getResourceAsStream("mybatis-config.xml");
  23. SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
  24. sqlSession = sqlSessionFactory.openSession();
  25. }
  26. @Test
  27. public void test() throws IOException {
  28. String sql = new SQL().SELECT("*").FROM("student").toString();
  29. System.out.println("sql = " + sql);
  30. }
  31. @After
  32. public void after() {
  33. if (null != sqlSession) {
  34. sqlSession.close();
  35. }
  36. }
  37. }

第四章:查询功能的实现

  • 步骤:
  • ① 定义功能类并提供获取查询的 SQL 语句的方法。
  • @SelectProvider 注解是用于生成查询的 SQL 语句的注解,其 type 属性是指定生成 SQL 语句功能类对象,method 属性是指定调用方法。
  • 示例:
  • SqlProvider.java
  1. package com.github.sql;
  2. import org.apache.ibatis.jdbc.SQL;
  3. /**
  4. * @author 许大仙
  5. * @version 1.0
  6. * @since 2021-11-02 13:51
  7. */
  8. public class SqlProvider {
  9. /**
  10. * 定义方法,返回查询的SQL语句
  11. *
  12. * @return
  13. */
  14. public static String findAll() {
  15. return new SQL().SELECT("*").FROM("student").toString();
  16. }
  17. }
  • StudentMapper.java
  1. package com.github.mapper;
  2. import com.github.entity.Student;
  3. import com.github.sql.SqlProvider;
  4. import org.apache.ibatis.annotations.Mapper;
  5. import org.apache.ibatis.annotations.SelectProvider;
  6. import java.util.List;
  7. /**
  8. * @author 许大仙
  9. * @version 1.0
  10. * @since 2021-11-02 11:09
  11. */
  12. @Mapper
  13. public interface StudentMapper {
  14. @SelectProvider(type = SqlProvider.class, method = "findAll")
  15. List<Student> findAll();
  16. }
  • 测试:
  1. package com.github.mybatis;
  2. import com.github.entity.Student;
  3. import com.github.mapper.StudentMapper;
  4. import org.apache.ibatis.io.Resources;
  5. import org.apache.ibatis.session.SqlSession;
  6. import org.apache.ibatis.session.SqlSessionFactory;
  7. import org.apache.ibatis.session.SqlSessionFactoryBuilder;
  8. import org.junit.After;
  9. import org.junit.Before;
  10. import org.junit.Test;
  11. import java.io.IOException;
  12. import java.io.InputStream;
  13. import java.util.List;
  14. /**
  15. * @author 许大仙
  16. * @version 1.0
  17. * @since 2021-10-29 14:19
  18. */
  19. public class MybatisTest {
  20. SqlSession sqlSession;
  21. @Before
  22. public void before() throws IOException {
  23. // 使用Mybatis的Resources读取mybatis-config.xml配置文件
  24. InputStream resourceAsStream = Resources.getResourceAsStream("mybatis-config.xml");
  25. SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
  26. sqlSession = sqlSessionFactory.openSession();
  27. }
  28. @Test
  29. public void test() throws IOException {
  30. StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
  31. List<Student> studentList = studentMapper.findAll();
  32. studentList.forEach(System.out::println);
  33. }
  34. @After
  35. public void after() {
  36. if (null != sqlSession) {
  37. sqlSession.close();
  38. }
  39. }
  40. }

第五章:新增功能的实现

  • 步骤:
  • ① 定义功能类并提供获取查询的 SQL 语句的方法。
  • @InsertProvider 注解是用于生成新增的 SQL 语句的注解,其 type 属性是指定生成 SQL 语句功能类对象,method 属性是指定调用方法。

  • 示例:

  • SqlProvider.java
  1. package com.github.sql;
  2. import org.apache.ibatis.jdbc.SQL;
  3. /**
  4. * @author 许大仙
  5. * @version 1.0
  6. * @since 2021-11-02 13:51
  7. */
  8. public class SqlProvider {
  9. /**
  10. * 定义方法,返回新增的SQL语句
  11. *
  12. * @return
  13. */
  14. public static String insert() {
  15. return new SQL().INSERT_INTO("student").VALUES("name", "#{name}").VALUES("age", "#{age}").toString();
  16. }
  17. }
  • StudentMapper.jaava
  1. package com.github.mapper;
  2. import com.github.entity.Student;
  3. import com.github.sql.SqlProvider;
  4. import org.apache.ibatis.annotations.InsertProvider;
  5. import org.apache.ibatis.annotations.Mapper;
  6. /**
  7. * @author 许大仙
  8. * @version 1.0
  9. * @since 2021-11-02 11:09
  10. */
  11. @Mapper
  12. public interface StudentMapper {
  13. @InsertProvider(type = SqlProvider.class, method = "insert")
  14. void insert(Student student);
  15. }
  • 测试:
  1. package com.github.mybatis;
  2. import com.github.entity.Student;
  3. import com.github.mapper.StudentMapper;
  4. import org.apache.ibatis.io.Resources;
  5. import org.apache.ibatis.session.SqlSession;
  6. import org.apache.ibatis.session.SqlSessionFactory;
  7. import org.apache.ibatis.session.SqlSessionFactoryBuilder;
  8. import org.junit.After;
  9. import org.junit.Before;
  10. import org.junit.Test;
  11. import java.io.IOException;
  12. import java.io.InputStream;
  13. /**
  14. * @author 许大仙
  15. * @version 1.0
  16. * @since 2021-10-29 14:19
  17. */
  18. public class MybatisTest {
  19. SqlSession sqlSession;
  20. @Before
  21. public void before() throws IOException {
  22. // 使用Mybatis的Resources读取mybatis-config.xml配置文件
  23. InputStream resourceAsStream = Resources.getResourceAsStream("mybatis-config.xml");
  24. SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
  25. sqlSession = sqlSessionFactory.openSession(true);
  26. }
  27. @Test
  28. public void test() throws IOException {
  29. StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
  30. Student student = new Student();
  31. student.setName("王八");
  32. student.setAge(19);
  33. studentMapper.insert(student);
  34. }
  35. @After
  36. public void after() {
  37. if (null != sqlSession) {
  38. sqlSession.close();
  39. }
  40. }
  41. }

第六章:更新功能的实现

  • 步骤:
  • ① 定义功能类并提供获取查询的 SQL 语句的方法。
  • @UpdateProvider 注解是用于生成修改的 SQL 语句的注解,其 type 属性是指定生成 SQL 语句功能类对象,method 属性是指定调用方法。

  • 示例:

  • SqlProvider.java
  1. package com.github.sql;
  2. import org.apache.ibatis.jdbc.SQL;
  3. /**
  4. * @author 许大仙
  5. * @version 1.0
  6. * @since 2021-11-02 13:51
  7. */
  8. public class SqlProvider {
  9. /**
  10. * 定义方法,返回更新的SQL语句
  11. *
  12. * @return
  13. */
  14. public static String update() {
  15. return new SQL().UPDATE("student").SET("name=#{name}").SET("age=#{age}").WHERE("id = #{id}").toString();
  16. }
  17. }
  • StudentMapper.java
  1. package com.github.mapper;
  2. import com.github.entity.Student;
  3. import com.github.sql.SqlProvider;
  4. import org.apache.ibatis.annotations.Mapper;
  5. import org.apache.ibatis.annotations.UpdateProvider;
  6. /**
  7. * @author 许大仙
  8. * @version 1.0
  9. * @since 2021-11-02 11:09
  10. */
  11. @Mapper
  12. public interface StudentMapper {
  13. @UpdateProvider(type = SqlProvider.class, method = "update")
  14. void update(Student student);
  15. }
  • 测试:
  1. package com.github.mybatis;
  2. import com.github.entity.Student;
  3. import com.github.mapper.StudentMapper;
  4. import org.apache.ibatis.io.Resources;
  5. import org.apache.ibatis.session.SqlSession;
  6. import org.apache.ibatis.session.SqlSessionFactory;
  7. import org.apache.ibatis.session.SqlSessionFactoryBuilder;
  8. import org.junit.After;
  9. import org.junit.Before;
  10. import org.junit.Test;
  11. import java.io.IOException;
  12. import java.io.InputStream;
  13. /**
  14. * @author 许大仙
  15. * @version 1.0
  16. * @since 2021-10-29 14:19
  17. */
  18. public class MybatisTest {
  19. SqlSession sqlSession;
  20. @Before
  21. public void before() throws IOException {
  22. // 使用Mybatis的Resources读取mybatis-config.xml配置文件
  23. InputStream resourceAsStream = Resources.getResourceAsStream("mybatis-config.xml");
  24. SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
  25. sqlSession = sqlSessionFactory.openSession(true);
  26. }
  27. @Test
  28. public void test() throws IOException {
  29. StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
  30. Student student = new Student();
  31. student.setId(1);
  32. student.setName("王八");
  33. student.setAge(19);
  34. studentMapper.update(student);
  35. }
  36. @After
  37. public void after() {
  38. if (null != sqlSession) {
  39. sqlSession.close();
  40. }
  41. }
  42. }

第七章:删除功能的实现

  • 步骤:
  • ① 定义功能类并提供获取查询的 SQL 语句的方法。
  • @DeleteProvider 注解是用于生成删除的 SQL 语句的注解,其 type 属性是指定生成 SQL 语句功能类对象,method 属性是指定调用方法。

  • 示例:

  • SqlProvider.java
  1. package com.github.sql;
  2. import org.apache.ibatis.jdbc.SQL;
  3. /**
  4. * @author 许大仙
  5. * @version 1.0
  6. * @since 2021-11-02 13:51
  7. */
  8. public class SqlProvider {
  9. /**
  10. * 定义方法,返回删除的SQL语句
  11. *
  12. * @return
  13. */
  14. public static String delete() {
  15. return new SQL().DELETE_FROM("student").WHERE("id = #{id}").toString();
  16. }
  17. }
  • StudentMapper.java
  1. package com.github.mapper;
  2. import com.github.sql.SqlProvider;
  3. import org.apache.ibatis.annotations.DeleteProvider;
  4. import org.apache.ibatis.annotations.Mapper;
  5. /**
  6. * @author 许大仙
  7. * @version 1.0
  8. * @since 2021-11-02 11:09
  9. */
  10. @Mapper
  11. public interface StudentMapper {
  12. @DeleteProvider(value = SqlProvider.class, method = "delete")
  13. void delete(Integer id);
  14. }
  • 测试:
  1. package com.github.mybatis;
  2. import com.github.mapper.StudentMapper;
  3. import org.apache.ibatis.io.Resources;
  4. import org.apache.ibatis.session.SqlSession;
  5. import org.apache.ibatis.session.SqlSessionFactory;
  6. import org.apache.ibatis.session.SqlSessionFactoryBuilder;
  7. import org.junit.After;
  8. import org.junit.Before;
  9. import org.junit.Test;
  10. import java.io.IOException;
  11. import java.io.InputStream;
  12. /**
  13. * @author 许大仙
  14. * @version 1.0
  15. * @since 2021-10-29 14:19
  16. */
  17. public class MybatisTest {
  18. SqlSession sqlSession;
  19. @Before
  20. public void before() throws IOException {
  21. // 使用Mybatis的Resources读取mybatis-config.xml配置文件
  22. InputStream resourceAsStream = Resources.getResourceAsStream("mybatis-config.xml");
  23. SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
  24. sqlSession = sqlSessionFactory.openSession(true);
  25. }
  26. @Test
  27. public void test() throws IOException {
  28. StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
  29. studentMapper.delete(1);
  30. }
  31. @After
  32. public void after() {
  33. if (null != sqlSession) {
  34. sqlSession.close();
  35. }
  36. }
  37. }