一、学习目标
spring整合MyBatis的原理主要涉及到将MyBatis的Mapper映射文件交由Spring容器管理,并将其注入到MyBatis的SqlSessionFactory中,从而实现两者的整合。
二、整合mybatis
1.写一个mybatis测试案例
项目结构:
1.数据库
sql
CREATE DATABASE `mybatis`;
USE `mybatis`;
create table Users(
id int not null auto_increment primary key,
name varchar(10) not null,
age int not null
);
insert into Users(id,name,age) values(null,'张三',20),(null,'李四',18);
2.实体类
java
public class User {
private int id; //id
private String name; //姓名
private int age; //密码
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public User(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
'}';
}
public User() {
}
}
2.编写接口
java
public interface UserMapper {
public List<User> selectUser();
}
3.mybatisConfig配置文件
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>
<typeAliases>
<package name="com.lzh.pojo"/>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=utf8&useSSL=false"/>
<property name="username" value="root"/>
<property name="password" value="admin123"/>
</dataSource>
</environment>
</environments>
<mappers>
<package name="com.lzh.dao"/>
</mappers>
</configuration>
4.UserrMapper文件:
XML
<?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.lzh.dao.UserMapper">
<select id="selectUser" resultType="User">
select * from users
</select>
</mapper>
5.pom.xml
XML
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.lzh</groupId>
<artifactId>spring-07</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.10.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.1.10.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.4</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.2</version>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
</project>
6.测试
java
@Test
public void selectUser() throws IOException {
String resource = "MybatisConfig.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> userList = mapper.selectUser();
for (User user: userList){
System.out.println(user);
}
sqlSession.close();
}
2.整合mybatis方式一
1.配置数据源
XML
<!--配置数据源->
定义一个数据源bean,id为"dataSource",用于管理数据库连接。
class属性指定了数据源的实现类为org.springframework.jdbc.datasource.DriverManagerDataSource,
-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<!--
设置数据库连接的URL。
- useSSL=true&useSSL=false:这里似乎有一个错误,通常只需要一个useSSL参数,并且应该保持一致。
对于本地开发,通常不需要SSL,所以应设置为false。
- useUnicode=true:指定使用Unicode字符集。
- characterEncoding=utf8:指定字符编码为UTF-8。注意,从MySQL 5.5.3版本开始,建议使用utf8mb4代替utf8,
以支持更广泛的Unicode字符,包括emoji表情等。
-->
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=false&useUnicode=true&characterEncoding=utf8"/>
<property name="username" value="root"/>
<property name="password" value="admin123"/>
</bean>
2.配置SqlSessionFactory,关联MyBatis注册,sqlSessionTemplate,关联sqlSessionFactory
XML
<!-- 配置SqlSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 注入数据源,这里的ref指向之前定义的数据源bean -->
<property name="dataSource" ref="dataSource"/>
<!-- 关联Mybatis的全局配置文件,MybatisConfig.xml中包含了MyBatis的设置,如别名、类型处理器、插件等 -->
<property name="configLocation" value="classpath:MybatisConfig.xml"/>
<!-- 指定Mapper XML文件的位置,MyBatis会根据这些XML文件来创建Mapper接口的实现 -->
<!-- 注意:这里只指定了一个Mapper XML文件,如果有多个,可以使用逗号分隔或者使用通配符 -->
<property name="mapperLocations" value="classpath:com/lzh/dao/UserMapper.xml"/>
</bean>
<!-- 注册sqlSessionTemplate,关联sqlSessionFactory -->
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<!-- 通过构造器注入SqlSessionFactory,使得SqlSessionTemplate能够管理SqlSession -->
<!-- index="0"指定了构造器参数的索引,这里假设SqlSessionTemplate的构造器第一个参数就是SqlSessionFactory -->
<constructor-arg index="0" ref="sqlSessionFactory"/>
</bean>
3.增加接口实现类
java
public class UserDaoImpl implements UserMapper {
// 注入SqlSessionTemplate,Spring容器会负责注入
private SqlSessionTemplate sqlSession;
// 通过构造器注入SqlSessionTemplate(推荐的方式,因为它支持Spring的依赖注入最佳实践)
public void setSqlSession(SqlSessionTemplate sqlSession) {
this.sqlSession = sqlSession;
}
public List<User> selectUser() {
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
return mapper.selectUser();
}
}
4.注册bean
XML
<bean id="userDao" class="com.lzh.dao.UserDaoImpl">
<property name="sqlSession" ref="sqlSession"/>
</bean>
5.修改mybatis配置文件
XML
<!--mappers>
<package name="com.lzh.dao"/>
</mappers-->
6.测试
java
@Test
public void test2(){
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
UserMapper mapper = (UserMapper) context.getBean("userDao");
List<User> user = mapper.selectUser();
System.out.println(user);
}
2.整合mybatis方式二
1.修改接口实现类
java
public class UserDaoImpl extends SqlSessionDaoSupport implements UserMapper {
public List<User> selectUser() {
UserMapper mapper = getSqlSession().getMapper(UserMapper.class);
return mapper.selectUser();
}
}
2.修改bean配置
XML
<!-- 注册sqlSessionTemplate,关联sqlSessionFactory -->
<!--bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
< 通过构造器注入SqlSessionFactory,使得SqlSessionTemplate能够管理SqlSession -->
<!-- index="0"指定了构造器参数的索引,这里假设SqlSessionTemplate的构造器第一个参数就是SqlSessionFactory -->
<!--constructor-arg index="0" ref="sqlSessionFactory"/>
</bean-->
<!--bean id="userDao" class="com.lzh.dao.UserDaoImpl">
<property name="sqlSession" ref="sqlSession"/>
</bean-->
<bean id="userDao" class="com.lzh.dao.UserDaoImpl">
<property name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean>