食之无味,弃之可惜。
第一章: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 脚本
DROP TABLE IF EXISTS `student`;
CREATE TABLE `student` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键',
`name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '学生姓名',
`age` int(11) NULL DEFAULT NULL COMMENT '学生年龄',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 3 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;
INSERT INTO `student` VALUES (1, '张三', 20);
INSERT INTO `student` VALUES (2, '李四', 25);
2.3 环境搭建
- build.gradle
plugins {
id 'war'
id 'java'
}
group 'org.example'
version '1.0'
repositories {
mavenLocal()
mavenCentral()
}
dependencies {
/* Junit单元测试 */
testImplementation 'junit:junit:4.13.2'
/* Mybatis */
implementation 'org.mybatis:mybatis:3.5.7'
/* MySQL */
implementation 'mysql:mysql-connector-java:8.0.26'
/* 数据源 */
implementation 'com.alibaba:druid:1.2.8'
/* 日志 */
implementation 'log4j:log4j:1.2.17'
}
- log4j.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
<appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
<param name="Encoding" value="UTF-8"/>
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%-5p %d{MM-dd HH:mm:ss,SSS} %m (%F:%L) \n"/>
</layout>
</appender>
<logger name="java.sql">
<level value="debug"/>
</logger>
<logger name="org.apache.ibatis">
<level value="info"/>
</logger>
<root>
<level value="debug"/>
<appender-ref ref="STDOUT"/>
</root>
</log4j:configuration>
- mybatis-config.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>
<!-- environments表示配置Mybatis的开发环境,可以配置多个环境,在众多具体环境中,使用default属性指定实际运行时使用的环境。default属性的取值是environment标签的id属性的值。 -->
<environments default="development">
<!-- environment表示配置Mybatis的一个具体的环境 -->
<environment id="development">
<!-- Mybatis的内置的事务管理器 -->
<transactionManager type="JDBC"/>
<!-- 配置数据源 -->
<dataSource type="POOLED">
<!-- 建立数据库连接的具体信息 -->
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/test"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<mappers>
<package name="com.github.mapper"/>
</mappers>
</configuration>
- Student.java
package com.github.entity;
import java.io.Serializable;
/**
* @author 许大仙
* @version 1.0
* @since 2021-11-02 11:06
*/
public class Student implements Serializable {
private Integer id;
private String name;
private Integer age;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "Student{" + "id=" + id + ", name='" + name + '\'' + ", age=" + age + '}';
}
}
第三章:使用 SQL 功能类构建 SQL 语句
- 示例:
package com.github.mybatis;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.jdbc.SQL;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
/**
* @author 许大仙
* @version 1.0
* @since 2021-10-29 14:19
*/
public class MybatisTest {
SqlSession sqlSession;
@Before
public void before() throws IOException {
// 使用Mybatis的Resources读取mybatis-config.xml配置文件
InputStream resourceAsStream = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
sqlSession = sqlSessionFactory.openSession();
}
@Test
public void test() throws IOException {
String sql = new SQL().SELECT("*").FROM("student").toString();
System.out.println("sql = " + sql);
}
@After
public void after() {
if (null != sqlSession) {
sqlSession.close();
}
}
}
第四章:查询功能的实现
- 步骤:
- ① 定义功能类并提供获取查询的 SQL 语句的方法。
- ②
@SelectProvider
注解是用于生成查询的 SQL 语句的注解,其 type 属性是指定生成 SQL 语句功能类对象,method 属性是指定调用方法。
- 示例:
- SqlProvider.java
package com.github.sql;
import org.apache.ibatis.jdbc.SQL;
/**
* @author 许大仙
* @version 1.0
* @since 2021-11-02 13:51
*/
public class SqlProvider {
/**
* 定义方法,返回查询的SQL语句
*
* @return
*/
public static String findAll() {
return new SQL().SELECT("*").FROM("student").toString();
}
}
- StudentMapper.java
package com.github.mapper;
import com.github.entity.Student;
import com.github.sql.SqlProvider;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.SelectProvider;
import java.util.List;
/**
* @author 许大仙
* @version 1.0
* @since 2021-11-02 11:09
*/
@Mapper
public interface StudentMapper {
@SelectProvider(type = SqlProvider.class, method = "findAll")
List<Student> findAll();
}
- 测试:
package com.github.mybatis;
import com.github.entity.Student;
import com.github.mapper.StudentMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
/**
* @author 许大仙
* @version 1.0
* @since 2021-10-29 14:19
*/
public class MybatisTest {
SqlSession sqlSession;
@Before
public void before() throws IOException {
// 使用Mybatis的Resources读取mybatis-config.xml配置文件
InputStream resourceAsStream = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
sqlSession = sqlSessionFactory.openSession();
}
@Test
public void test() throws IOException {
StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
List<Student> studentList = studentMapper.findAll();
studentList.forEach(System.out::println);
}
@After
public void after() {
if (null != sqlSession) {
sqlSession.close();
}
}
}
第五章:新增功能的实现
- 步骤:
- ① 定义功能类并提供获取查询的 SQL 语句的方法。
②
@InsertProvider
注解是用于生成新增的 SQL 语句的注解,其 type 属性是指定生成 SQL 语句功能类对象,method 属性是指定调用方法。示例:
- SqlProvider.java
package com.github.sql;
import org.apache.ibatis.jdbc.SQL;
/**
* @author 许大仙
* @version 1.0
* @since 2021-11-02 13:51
*/
public class SqlProvider {
/**
* 定义方法,返回新增的SQL语句
*
* @return
*/
public static String insert() {
return new SQL().INSERT_INTO("student").VALUES("name", "#{name}").VALUES("age", "#{age}").toString();
}
}
- StudentMapper.jaava
package com.github.mapper;
import com.github.entity.Student;
import com.github.sql.SqlProvider;
import org.apache.ibatis.annotations.InsertProvider;
import org.apache.ibatis.annotations.Mapper;
/**
* @author 许大仙
* @version 1.0
* @since 2021-11-02 11:09
*/
@Mapper
public interface StudentMapper {
@InsertProvider(type = SqlProvider.class, method = "insert")
void insert(Student student);
}
- 测试:
package com.github.mybatis;
import com.github.entity.Student;
import com.github.mapper.StudentMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
/**
* @author 许大仙
* @version 1.0
* @since 2021-10-29 14:19
*/
public class MybatisTest {
SqlSession sqlSession;
@Before
public void before() throws IOException {
// 使用Mybatis的Resources读取mybatis-config.xml配置文件
InputStream resourceAsStream = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
sqlSession = sqlSessionFactory.openSession(true);
}
@Test
public void test() throws IOException {
StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
Student student = new Student();
student.setName("王八");
student.setAge(19);
studentMapper.insert(student);
}
@After
public void after() {
if (null != sqlSession) {
sqlSession.close();
}
}
}
第六章:更新功能的实现
- 步骤:
- ① 定义功能类并提供获取查询的 SQL 语句的方法。
②
@UpdateProvider
注解是用于生成修改的 SQL 语句的注解,其 type 属性是指定生成 SQL 语句功能类对象,method 属性是指定调用方法。示例:
- SqlProvider.java
package com.github.sql;
import org.apache.ibatis.jdbc.SQL;
/**
* @author 许大仙
* @version 1.0
* @since 2021-11-02 13:51
*/
public class SqlProvider {
/**
* 定义方法,返回更新的SQL语句
*
* @return
*/
public static String update() {
return new SQL().UPDATE("student").SET("name=#{name}").SET("age=#{age}").WHERE("id = #{id}").toString();
}
}
- StudentMapper.java
package com.github.mapper;
import com.github.entity.Student;
import com.github.sql.SqlProvider;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.UpdateProvider;
/**
* @author 许大仙
* @version 1.0
* @since 2021-11-02 11:09
*/
@Mapper
public interface StudentMapper {
@UpdateProvider(type = SqlProvider.class, method = "update")
void update(Student student);
}
- 测试:
package com.github.mybatis;
import com.github.entity.Student;
import com.github.mapper.StudentMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
/**
* @author 许大仙
* @version 1.0
* @since 2021-10-29 14:19
*/
public class MybatisTest {
SqlSession sqlSession;
@Before
public void before() throws IOException {
// 使用Mybatis的Resources读取mybatis-config.xml配置文件
InputStream resourceAsStream = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
sqlSession = sqlSessionFactory.openSession(true);
}
@Test
public void test() throws IOException {
StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
Student student = new Student();
student.setId(1);
student.setName("王八");
student.setAge(19);
studentMapper.update(student);
}
@After
public void after() {
if (null != sqlSession) {
sqlSession.close();
}
}
}
第七章:删除功能的实现
- 步骤:
- ① 定义功能类并提供获取查询的 SQL 语句的方法。
②
@DeleteProvider
注解是用于生成删除的 SQL 语句的注解,其 type 属性是指定生成 SQL 语句功能类对象,method 属性是指定调用方法。示例:
- SqlProvider.java
package com.github.sql;
import org.apache.ibatis.jdbc.SQL;
/**
* @author 许大仙
* @version 1.0
* @since 2021-11-02 13:51
*/
public class SqlProvider {
/**
* 定义方法,返回删除的SQL语句
*
* @return
*/
public static String delete() {
return new SQL().DELETE_FROM("student").WHERE("id = #{id}").toString();
}
}
- StudentMapper.java
package com.github.mapper;
import com.github.sql.SqlProvider;
import org.apache.ibatis.annotations.DeleteProvider;
import org.apache.ibatis.annotations.Mapper;
/**
* @author 许大仙
* @version 1.0
* @since 2021-11-02 11:09
*/
@Mapper
public interface StudentMapper {
@DeleteProvider(value = SqlProvider.class, method = "delete")
void delete(Integer id);
}
- 测试:
package com.github.mybatis;
import com.github.mapper.StudentMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
/**
* @author 许大仙
* @version 1.0
* @since 2021-10-29 14:19
*/
public class MybatisTest {
SqlSession sqlSession;
@Before
public void before() throws IOException {
// 使用Mybatis的Resources读取mybatis-config.xml配置文件
InputStream resourceAsStream = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
sqlSession = sqlSessionFactory.openSession(true);
}
@Test
public void test() throws IOException {
StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
studentMapper.delete(1);
}
@After
public void after() {
if (null != sqlSession) {
sqlSession.close();
}
}
}