抱歉,您的浏览器无法访问本站
本页面需要浏览器支持(启用)JavaScript
了解详情 >

摘要:本文学习了如何在Spring框架中整合MyBatis框架。

环境

Windows 10 企业版 LTSC 21H2
MySQL 5.7.40
Java 1.8
Tomcat 8.5.50
Maven 3.6.3
Spring 5.2.25.RELEASE
MyBatis 3.5.6

1 概述

分工:

  • Spring是核心容器,负责对象管理、依赖注入、事务控制等核心功能。
  • MyBatis是持久层框架,负责数据访问、持久化等功能。

整合后可以让Spring管理MyBatis的对象,并通过依赖注入的方式使用MyBatis的功能。

2 目录结构

目录结构如下:

code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
demo-ssm/
├── src/
│ ├── main/
│ │ ├── java/
│ │ │ └── com/example/
│ │ │ ├── config/
│ │ │ │ ├── RootConfig.java
│ │ │ ├── entity/
│ │ │ │ └── User.java
│ │ │ ├── mapper/
│ │ │ │ ├── UserMapper.java
│ │ │ │ └── UserMapper.xml
│ │ │ ├── service/
│ │ │ │ └── UserService.java
│ │ │ └── DemoApplication.java
│ │ └── resources/
│ │ └── jdbc.properties
└── pom.xml

3 创建配置文件

创建Maven项目,并创建pom.xml文件:

pom.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.example</groupId>
<artifactId>demo-spring-mybatis</artifactId>
<version>1.0.0-SNAPSHOT</version>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.target>1.8</maven.compiler.target>
<maven.compiler.source>1.8</maven.compiler.source>
</properties>

<dependencies>
<!-- Spring Context -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.25.RELEASE</version>
</dependency>
<!-- Spring JDBC -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.25.RELEASE</version>
</dependency>
<!-- MyBatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.13</version>
</dependency>
<!-- MyBatis-Spring -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.1.1</version>
</dependency>
<!-- MySQL -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.49</version>
</dependency>
<!-- Druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.8</version>
</dependency>
</dependencies>

<build>
<resources>
<!-- 保留默认的资源目录 -->
<resource>
<directory>src/main/resources</directory>
</resource>
<!-- 额外添加XML文件 -->
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
<!-- 禁止Maven替换XML中的占位符,交由MyBatis处理 -->
<filtering>false</filtering>
</resource>
</resources>
</build>
</project>

创建jdbc.properties文件:

jdbc.properties
1
2
3
4
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/test?useSSL=false&serverTimezone=GMT%2B8
jdbc.username=root
jdbc.password=123456

4 创建配置类

创建根容器配置类:

java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
@Configuration
@EnableTransactionManagement
@PropertySource("classpath:jdbc.properties")
@MapperScan("com.example.mapper")
@ComponentScan(
basePackages = "com.example",
excludeFilters = @ComponentScan.Filter(type = FilterType.ANNOTATION, value = Controller.class)
)
public class RootConfig {
@Resource
private Environment env;
// 配置数据连接
@Bean
public DataSource dataSource() {
DruidDataSource dataSource = new DruidDataSource();
dataSource.setDriverClassName(env.getProperty("jdbc.driverClass"));
dataSource.setUrl(env.getProperty("jdbc.url"));
dataSource.setUsername(env.getProperty("jdbc.username"));
dataSource.setPassword(env.getProperty("jdbc.password"));
return dataSource;
}
// 配置会话工厂
@Bean
public SqlSessionFactory sqlSessionFactory() throws Exception {
// 创建会话工厂
SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
// 设置数据源
factoryBean.setDataSource(dataSource());
// 设置映射文件路径
factoryBean.setMapperLocations(new ClassPathResource("com/example/mapper/UserMapper.xml"));
// 返回会话工厂
return factoryBean.getObject();
}
// 配置会话模板
@Bean
public SqlSessionTemplate sqlSessionTemplate() throws Exception {
return new SqlSessionTemplate(sqlSessionFactory());
}
// 配置事务管理器
@Bean
public PlatformTransactionManager transactionManager() {
return new DataSourceTransactionManager(dataSource());
}
// 配置事务模板
@Bean
public TransactionTemplate transactionTemplate() {
return new TransactionTemplate(transactionManager());
}
}

5 创建业务类

创建User类:

java
1
2
3
4
5
6
7
public class User {
private Integer id;
private String name;
private Integer age;
private String email;
// ...
}

创建UserMapper接口:

java
1
2
3
public interface UserMapper {
List<User> selectUserList();
}

创建UserMapper映射文件:

UserMapper.xml
1
2
3
4
5
6
7
8
9
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- 指定接口全类名 -->
<mapper namespace="com.example.mapper.UserMapper">
<!-- 配置SQL语句 -->
<select id="selectUserList" resultType="com.example.entity.User">
SELECT * FROM user
</select>
</mapper>

创建UserService类:

java
1
2
3
4
5
6
7
8
9
@Service
@Transactional
public class UserService {
@Resource
private UserMapper userMapper;
public List<User> findUserList() {
return userMapper.selectUserList();
}
}

创建启动类:

java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class DemoApplication {
public static void main(String[] args) {
// 加载配置类
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(RootConfig.class);
// 获取UserService对象
UserService userService = context.getBean(UserService.class);
// 执行查询
List<User> userList = userService.findUserList();
// 打印结果
userList.forEach(System.out::println);
// 关闭容器
context.close();
}
}

评论