MyBatis-Spring 会帮助你将 MyBatis 代码无缝地整合到 Spring 中。它将允许 MyBatis 参与到 Spring 的事务管理之中,创建映射器 mapper
和 SqlSession
并注入到 bean 中,以及将 Mybatis 的异常转换为 Spring 的 DataAccessException
。最终,可以做到应用代码不依赖于 MyBatis,Spring 或 MyBatis-Spring。
详情请参照官网
pom.xml
<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.0modelVersion>
<groupId>com.ganggroupId>
<artifactId>spring-mybatisartifactId>
<version>1.0-SNAPSHOTversion>
<dependencies>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<version>1.18.8version>
dependency>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.12version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.5.2version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.47version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webmvcartifactId>
<version>5.1.10.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-jdbcartifactId>
<version>5.1.10.RELEASEversion>
dependency>
<dependency>
<groupId>org.aspectjgroupId>
<artifactId>aspectjweaverartifactId>
<version>1.9.4version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatis-springartifactId>
<version>2.0.2version>
dependency>
dependencies>
<build>
<resources>
<resource>
<directory>src/main/javadirectory>
<includes>
<include>**/*.propertiesinclude>
<include>**/*.xmlinclude>
includes>
<filtering>truefiltering>
resource>
resources>
build>
project>
创建一个实体类:注意对应自己数据库里的字段
package com.gang.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/*
Description:实体类
Author:32259
Time:2020二月2020/2/2514:18
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
private int id;
private String name;
private String pwd;
}
定义一个接口:
package com.gang.mapper;
/*
Description:接口
Author:32259
Time:2020二月2020/2/2514:22
*/
import com.gang.pojo.User;
import java.util.List;
public interface UserMapper {
//查询用户
public List<User> getUserList();
}
接口的实现类:
package com.gang.mapper.impl;
/*
Description:实现类
Author:32259
Time:2020二月2020/2/2514:39
*/
import com.gang.mapper.UserMapper;
import com.gang.pojo.User;
import org.mybatis.spring.SqlSessionTemplate;
import java.util.List;
public class UserMapperImpl implements UserMapper {
//注入sqlSession
private SqlSessionTemplate sqlSession;
public List<User> getUserList() {
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
return mapper.getUserList();
}
//set方法一定要有 set方式注入
public void setSqlSession(SqlSessionTemplate sqlSession) {
this.sqlSession = sqlSession;
}
}
UserMapper.xml
<mapper namespace="com.gang.mapper.UserMapper">
<select id="getUserList" resultType="User">
select * from user;
select>
mapper>
mybatis的配置文件就不需要了,全部在spring的配置文件里面写,一个就够了
applicationContext.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
https://www.springframework.org/schema/tx/spring-tx.xsd">
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=utf8"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="typeAliasesPackage" value="com.gang.pojo"/>
<property name="mapperLocations" value="classpath:com/gang/mapper/xml/*.xml"/>
bean>
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index="0" ref="sqlSessionFactory"/>
bean>
<bean id="userMapperImpl" class="com.gang.mapper.impl.UserMapperImpl">
<property name="sqlSession" ref="sqlSession"/>
bean>
beans>
/*
Description:测试类
Author:32259
Time:2020二月2020/2/2514:50
*/
import com.gang.mapper.UserMapper;
import com.gang.mapper.impl.UserMapperImpl;
import com.gang.pojo.User;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.junit.Test;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.util.List;
public class MyTest {
@Test
public void test1(){
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
UserMapper userMapperImpl = (UserMapper) context.getBean("userMapperImpl");
List<User> userList = userMapperImpl.getUserList();
for (User user : userList) {
System.out.println(user);
}
}
}
有关事务,我这里就不在赘述了,以前写过关于事务介绍的一篇博客,大家有兴趣可以看一看传送门
刚才我们就只演示了一下查询功能,这个是不需要开启事务的!
现在我们要想增加或者删除一些数据,这时候我们就需要开启事务了!
接口:
//增加用户
int addUser(User user);
//删除用户
int deleteUser(int id);
接口实现类:重写方法
//在一个方法里面,要么一起成功,要么一起失败,开启事务
public List<User> getUserList() {
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = new User(4, "二锤子", "123456");
mapper.addUser(user);
mapper.deleteUser(3);
return mapper.getUserList();
}
//注意,我改了一下查询的方法,我想让它先给我增加一个4号用户,再删除3号用户,然后把查询的结果返回给我
//一个失败了另一个就不会成功
public int addUser(User user) {
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
return mapper.addUser(user);
}
public int deleteUser(int id) {
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
return mapper.deleteUser(id);
}
注意,这一次我故意将删除的sql写错,看增加功能能否成功执行
带大家体验一下事务!
<?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.gang.mapper.UserMapper">
<select id="getUserList" resultType="User">
select * from user;
</select>
<insert id="addUser" parameterType="User">
insert into user(id,name,pwd) values (#{id},#{name},#{pwd});
</insert>
<delete id="deleteUser" parameterType="int">
<!--注意,这里我故意将删除的sql写错,看增加功能能否成功执行-->
deletes from user where id=#{id};
</delete>
</mapper>
这里只增加了开启事务的配置,直接加在里面即可,顺序不影响。
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<constructor-arg ref="dataSource" />
bean>
<tx:advice id="interceptor" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="*" propagation="REQUIRED"/>
tx:attributes>
tx:advice>
<aop:config>
<aop:pointcut id="txPointCut" expression="execution(* com.gang.mapper.*.*(..))"/>
<aop:advisor advice-ref="interceptor" pointcut-ref="txPointCut"/>
aop:config>
结果:这里删除的sql写错了,肯定是不能成功,我们要看的是添加功能有没有成功!
打开数据库的表,发现没有变化(因为这里我们开起了事务,要么一起成功,要么一起失败)
我们先把上面spring的配置文件里开启事务的配置注掉,运行测试类看结果:
没错,它也报了相同的错误,都是sql的问题,很多同学可能说这不是一样吗,有啥用这个事务。
没错,睁大眼睛好好看,程序虽然报错了但是数据还是增加成功了,删除功能有问题,但是不影响我增加功能的正常运作,这是我们不希望看到的情况,我们想让他们一荣俱荣一损俱损,整整齐齐的,这就是事物的作用!
好了,踩过前面两个坑之后,我们就将正确的程序运行一下
注意:将事务开启,sql改正确
还有一个要改的点就是我们刚才已经插入了一条id=4的数据,我们这时候如果还要插入id=4的数据,这肯定是行不通的,会报错!
public List<User> getUserList() {
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
//插入id=5的数据,后面改不改无所谓,为了效果更清晰,这里也改一下
User user = new User(5, "精神小伙", "123456");
mapper.addUser(user);
//把刚才插入的数据删除
mapper.deleteUser(4);
return mapper.getUserList();
}
好,我们再瞄一眼数据库:
可以看到我们的4号选手二锤子已经被删了,而5号选手精神小伙已经加入了队伍
OK,我们下篇见!