?MyBatis 是一款优秀的持久层框架,它支持定制化 SQL、存储过程以及高级映射。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以使用简单的 XML 或注解来配置和映射原生信息,将接口和 Java 的 POJOs(Plain Ordinary Java Object,普通的 Java对象)映射成数据库中的记录。
学习了spring和mybatis之后,我们需要将mybatis整合到spring框架中去使用
现在我们通过一个小小的案例来学习spring与mybatis的整合
目录
准备阶段:
数据库准备:
????????在MySQL数据库中新建一个mybatis的数据库并添加一个user表
项目准备:
????????新建一个maven项目,连接上数据库
编码阶段:
一、在resource下引入mybatis的配置文件mybatis-config.xml及其配置文件db.properties
二、在main.java下建一个pojo包用来编写实体类User,建一个mapper包用来编写业务接口及其实现类
三、将mybatis交由spring管理
四、编写一个接口实现类UserMapperImpl实现该方法,有两种方法实现
五、将实现方法的实现类交给spring管理
测试阶段:
Test.java下使用Junit测试代码
准备阶段:
数据库准备:
????????在MySQL数据库中新建一个mybatis的数据库并添加一个user表
CREATE DATABASE mybatis;
USE mybatis;
INSERT INTO USER(id,NAME,psd) VALUES
(1,'郭靖','123456'),
(2,'黄蓉','520544'),
(3,'杨过','258852')
SELECT * FROM USER;
项目准备:
????????新建一个maven项目,连接上数据库
在user和password中输入自己的用户名和密码
?
点击schemas勾选mybatis
?
Apply--ok数据库即连接成功
导入依赖:在pom.xml文件中需要导入如下依赖
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.26</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.9</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.9</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.8.M1</version>
<scope>runtime</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.20</version>
<scope>provided</scope>
</dependency>
</dependencies>
?为了防止maven的资源过滤问题(导致java文件下的配置文件.xml被maven过滤掉)需要在pom.xml中加入下面的代码
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>
?最后为了防止出现编码问题pom.xml中还需加入
</properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
?至此我们的准备工作就最好了
编码阶段:
一、在resource下引入mybatis的配置文件mybatis-config.xml及其配置文件db.properties
????????mybatis-config.xml(在mybatis的官方文档中有)
<?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="pojo"/>
</typeAliases>
</configuration>
????????db.properties
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=utf-8
user=root
password=123456
二、在main.java下建一个pojo包用来编写实体类User,建一个mapper包用来编写业务接口及其实现类
????????1.User类(@Data是lombok下可以为该类自动生成getset方法的注解)
package pojo;
import lombok.Data;
@Data
public class User {
private int id;
private String name;
private String psd;
}
?????????2.编写业务接口UserMapper
package mapper;
import pojo.User;
import java.util.List;
public interface UserMapper {
//查找所有用户
List<User> selectAllUser();
}
??????? 3.编写业务接口对应映射文件UserMapper.xml
? ??????? 该模板mybatis官网有,namespace为映射文件的全类名,id为对应的方法名
<?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="mapper.UserMapper">
<select id="selectAllUser" resultType="user">
select * from mybatis.user;
</select>
</mapper>
三、将mybatis交由spring管理
?????? 1.创建spring-mapper.xml管理mybatis
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<!--读取 db.properties中的内容 property-placeholder:占位符 location:属性文件的位置 -->
<context:property-placeholder location="classpath:db.properties"/>
<!-- 1) 获得数据库连接池对象,并交由 spring 同一管理 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<!-- 连接数据库的驱动,连接字符串,用户名和登录密码-->
<property name="driverClassName" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${user}"/>
<property name="password" value="${password}"/>
</bean>
<!-- 2) 获取 SqlSessionFactory 对象,并交由 spring 管理-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 注入连接池-->
<property name="dataSource" ref="dataSource"/>
<!-- 注入 mybatis配置文件 映射文件mapper -->
<property name="configLocation" value="classpath:mybatis-config.xml"></property>
<property name="mapperLocations" value="classpath:mapper/*.xml"/>
</bean>
<!-- 3) 获取 SqlSession 对象,并交由 spring 管理 用SqlSessionTemplate得到的SqlSession可以不用我们自己操心事务的管理,以及关闭操作-->
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<!-- 给 SqlSessionTemplate 的构造函数赋值-->
<constructor-arg index="0" ref="sqlSessionFactory" />
</bean>
</beans>
??????? 2.编写applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<!--引入mybatis-->
<import resource="spring-dao.xml"></import>
</beans>
这样mybatis就整合到spring中去了
四、编写一个接口实现类UserMapperImpl实现该方法,有两种方法实现
??????? 方法1.UserMapperImpl 使用SqlSessionTemplate????????
package mapper;
import org.mybatis.spring.SqlSessionTemplate;
import pojo.User;
import java.util.List;
public class UserMapperImpl implements UserMapper{
//sqlSessionTemplate相当于一个sqlSession模板 由于需要交给spring管理,所以需要创建这个类
private SqlSessionTemplate sqlSessionTemplate;
public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) {
this.sqlSessionTemplate = sqlSessionTemplate;
}
@Override
public List<User> selectAllUser() {
UserMapper mapper = sqlSessionTemplate.getMapper(UserMapper.class);
return mapper.selectAllUser();
}
}
??????? 方法2.UserMapperImpl2 继承SqlSessionDaoSupport
package mapper;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import pojo.User;
import java.util.List;
public class UserMapperImpl2 extends SqlSessionDaoSupport implements UserMapper {
@Override
public List<User> selectAllUser() {
SqlSession sqlSession = getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
return mapper.selectAllUser();
}
}
五、将实现方法的实现类交给spring管理
????????SqlSessionTemplate传递sqlSession
????????SqlSessionDaoSupport传递sqlSessionFactory,相当于这个类帮我们创建sqlSession,我们无须自己写SqlSessionTemplate的set方法
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<!--引入mybatis-->
<import resource="spring-dao.xml"></import>
<bean id="UserMapperImpl" class="mapper.UserMapperImpl">
<property name="sqlSessionTemplate" ref="sqlSession"></property>
</bean>
<bean id="UserMapperImpl2" class="mapper.UserMapperImpl2">
<property name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean>
</beans>
测试阶段:
Test.java下使用Junit测试代码
import mapper.UserMapper;
import mapper.UserMapperImpl;
import mapper.UserMapperImpl2;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import pojo.User;
import utils.MybatisUtil;
import java.util.List;
public class MyTest {
@Test
public void test(){
SqlSession sqlSession = MybatisUtil.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> userList = mapper.selectAllUser();
for (User user : userList) {
System.out.println(user);
}
sqlSession.close();
}
//spring管理后
@Test
public void selectAllUserTest(){
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
UserMapperImpl userMapperImpl = (UserMapperImpl) context.getBean("UserMapperImpl");
for (User user : userMapperImpl.selectAllUser()) {
System.out.println(user);
}
}
@Test
public void selectAllUserTest2() {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
UserMapperImpl2 userMapperImpl2 = context.getBean(UserMapperImpl2.class);
for (User user : userMapperImpl2.selectAllUser()) {
System.out.println(user);
}
}
}
????????测试成功:
?至此mybatis就整合到spring了
|