MyBatis5:MyBatis集成Spring事物管理(上篇)
前言
有些日子没写博客了,主要原因一个是工作,另一个就是健身,因为我们不仅需要努力工作,也需要有健康的身体嘛。
那有看LZ博客的网友朋友们放心,LZ博客还是会继续保持更新,只是最近两三个月LZ写博客相对会慢一些,博客的内容也会更偏向于实战一些,主要是对于工作中遇到一些比较实际性的问题进行总结与研究,并整理成文与网友朋友们分享。
灵感来源于生活,灵感也来源于工作,今天LZ博文的内容就是MyBatis与Spring事务集成的问题,后面的文章写作宗旨就是尽量写得详细点,把东西能给网友朋友们说清楚,OK,开始我们的内容。
单独使用MyBatis对事务进行管理
前面MyBatis的文章有写过相关内容,这里继续写一个最简单的Demo,算是复习一下之前MyBatis的内容吧,先是建表,建立一个简单的Student表:
create table student
(
student_id int auto_increment,
student_name varchar(20) not null,
primary key(student_id)
)
建立实体类Student.java:
public class Student
{
private int studentId;
private String studentName; public int getStudentId()
{
return studentId;
} public void setStudentId(int studentId)
{
this.studentId = studentId;
} public String getStudentName()
{
return studentName;
} public void setStudentName(String studentName)
{
this.studentName = studentName;
} public String toString()
{
return "Student{[studentId:" + studentId + "], [studentName:" + studentName + "]}";
}
}
多说一句,对实体类重写toString()方法,打印其中每一个(或者说是关键属性)是一个推荐的做法。接着是config.xml,里面是jdbc基本配置:
<?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>
<typeAlias alias="Student" type="org.xrq.domain.Student" />
</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/test"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments> <mappers>
<mapper resource="student_mapper.xml"/>
</mappers>
</configuration>
然后是student_mapper.xml,主要是具体的sql语句:
<mapper namespace="StudentMapper">
<resultMap type="Student" id="StudentMap">
<id column="student_id" property="studentId" jdbcType="INTEGER" />
<result column="student_name" property="studentName" jdbcType="VARCHAR" />
</resultMap> <select id="selectAllStudents" resultMap="StudentMap">
select student_id, student_name from student;
</select> <insert id="insertStudent" useGeneratedKeys="true" keyProperty="studentId" parameterType="Student">
insert into student(student_id, student_name) values(#{studentId, jdbcType=INTEGER}, #{studentName, jdbcType=VARCHAR});
</insert>
</mapper>
建立一个MyBatisUtil.java,用于建立一些MyBatis基本元素的,后面的类都继承这个类:
public class MyBatisUtil
{
protected static SqlSessionFactory ssf;
protected static Reader reader; static
{
try
{
reader = Resources.getResourceAsReader("config.xml");
ssf = new SqlSessionFactoryBuilder().build(reader);
}
catch (IOException e)
{
e.printStackTrace();
}
} protected SqlSession getSqlSession()
{
return ssf.openSession();
}
}
企业级开发讲求:
1、定义和实现分开
2、分层开发,通常情况下为Dao-->Service-->Controller,不排除根据具体情况多一层/几层或少一层
所以,先写一个StudentDao.java接口:
public interface StudentDao
{
public List<Student> selectAllStudents();
public int insertStudent(Student student);
}
最后写一个StudentDaoImpl.java实现这个接口,注意要继承MyBatisUtil.java类:
public class StudentDaoImpl extends MyBatisUtil implements StudentDao
{
private static final String NAMESPACE = "StudentMapper."; public List<Student> selectAllStudents()
{
SqlSession ss = getSqlSession();
List<Student> list = ss.selectList(NAMESPACE + "selectAllStudents");
ss.close();
return list;
} public int insertStudent(Student student)
{
SqlSession ss = getSqlSession();
int i = ss.insert(NAMESPACE + "insertStudent", student);
// ss.commit();
ss.close();
return i;
}
}
写一个测试类:
public class StudentTest
{
public static void main(String[] args)
{
StudentDao studentDao = new StudentDaoImpl(); Student student = new Student();
student.setStudentName("Jack"); studentDao.insertStudent(student);
System.out.println("插入的主键为:" + student.getStudentId()); System.out.println("-----Display students------");
List<Student> studentList = studentDao.selectAllStudents();
for (int i = 0, length = studentList.size(); i < length; i++)
System.out.println(studentList.get(i));
}
}
结果一定是空。
我说过这个例子既是作为复习,也是作为一个引子引入我们今天的内容,空的原因是,insert操作已经做了,但是MyBatis并不会帮我们自动提交事务,所以展示出来的自然是空的。这种时候就必须手动通过SqlSession的commit()方法提交事务,即打开StudentDaoImpl.java类第17行的注释就可以了。
多说一句,这个例子除了基本的MyBatis插入操作之外,在插入的基础上还有返回插入的主键id的功能。
接下来,就利用Spring管理MyBatis事务,这也是企业级开发中最常用的事务管理做法。
使用Spring管理MyBatis事务
关于这块,网上有很多文章讲解,我搜索了很多,但是要么就是相互复制黏贴,要么就是没有把整个例子讲清楚的,通过这一部分,我尽量讲清楚如何使用Spring管理MyBatis事务。
使用Spring管理MyBatis事务,除了Spring必要的模块beans、context、core、expression、commons-logging之外,还需要以下内容:
(1)MyBatis-Spring-1.x.0.jar,这个是Spring集成MyBatis必要的jar包
(2)数据库连接池,dbcp、c3p0都可以使用,我这里使用的是阿里的druid
(3)jdbc、tx、aop,jdbc是基本的不多说,用到tx和aop是因为Spring对MyBatis事务管理的支持是通过aop来实现的
(4)aopalliance.jar,这个是使用Spring AOP必要的一个jar包
上面的jar包会使用Maven的可以使用Maven下载,没用过Maven的可以去CSDN上下载,一搜索就有的。
MyBatis的配置文件config.xml里面,关于jdbc连接的部分可以都去掉,只保留typeAliases的部分:
<?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>
<typeAlias alias="Student" type="org.xrq.domain.Student" />
</typeAliases>
</configuration>
多提一句,MyBatis另外一个配置文件student_mapper.xml不需要改动。接着,写Spring的配置文件,我起名字叫做spring.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd"> <!-- 注解配置 -->
<tx:annotation-driven transaction-manager="transactionManager" />
<context:annotation-config />
<context:component-scan base-package="org.xrq" /> <!-- 数据库连接池,这里使用alibaba的Druid -->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
<property name="url" value="jdbc:mysql://localhost:3306/test" />
<property name="username" value="root" />
<property name="password" value="root" />
</bean> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="configLocation" value="classpath:config.xml" />
<property name="mapperLocations" value="classpath:*_mapper.xml" />
<property name="dataSource" ref="dataSource" />
</bean> <!-- 事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean> </beans>
这里面主要就是事务管理器和数据库连接池两部分的内容。
另外我们看到有一个SqlSessionFactory,使用过MyBatis的朋友们一定对这个类不陌生,它是用于配置MyBatis环境的,SqlSessionFactory里面有两个属性configLocation、mapperLocations,顾名思义分别代表配置文件的位置和映射文件的位置,这里只要路径配置正确,Spring便会自动去加载这两个配置文件了。
然后要修改的是Dao的实现类,此时不再继承之前的MyBatisUtil这个类,而是继承MyBatis-Spring-1.x.0.jar自带的SqlSessionDaoSupport.java,具体代码如下:
@Repository
public class StudentDaoImpl extends SqlSessionDaoSupport implements StudentDao
{
private static final String NAMESPACE = "StudentMapper."; @Resource
public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory)
{
super.setSqlSessionFactory(sqlSessionFactory);
} public List<Student> selectAllStudents()
{
return getSqlSession().selectList(NAMESPACE + "selectAllStudents");
} public int insertStudent(Student student)
{
return getSqlSession().insert(NAMESPACE + "insertStudent", student);
}
}
这里用到了两个注解,分别说一下。
(1)@Repository,这个注解和@Component、@Controller和我们最常见的@Service注解是一个作用,都可以将一个类声明为一个Spring的Bean。它们的区别到不在于具体的语义上,更多的是在于注解的定位上。之前说过,企业级应用注重分层开发的概念,因此,对这四个相似的注解应当有以下的理解:
- @Repository注解,对应的是持久层即Dao层,其作用是直接和数据库交互,通常来说一个方法对应一条具体的Sql语句
- @Service注解,对应的是服务层即Service层,其作用是对单条/多条Sql语句进行组合处理,当然如果简单的话就直接调用Dao层的某个方法了
- @Controller注解,对应的是控制层即MVC设计模式中的控制层,其作用是接收用户请求,根据请求调用不同的Service取数据,并根据需求对数据进行组合、包装返回给前端
- @Component注解,这个更多对应的是一个组件的概念,如果一个Bean不知道属于拿个层,可以使用@Component注解标注
这也体现了注解的其中一个优点:见名知意,即看到这个注解就大致知道这个类的作用即它在整个项目中的定位。
(2)@Resource,这个注解和@Autowired注解是一个意思,都可以自动注入属性属性。由于SqlSessionFactory是MyBatis的核心,它在spring.xml中又进行过了声明,因此这里通过@Resource注解将id为"sqlSessionFactory"的Bean给注入进来,之后就可以通过getSqlSession()方法获取到SqlSession并进行数据的增、删、改、查了。
最后无非就是写一个测试类测试一下:
public class StudentTest
{
public static void main(String[] args)
{
ApplicationContext ac = new ClassPathXmlApplicationContext("spring.xml");
StudentDao studentDao = (StudentDao)ac.getBean("studentDaoImpl"); Student student = new Student();
student.setStudentName("Lucy"); int j = studentDao.insertStudent(student);
System.out.println("j = " + j + "\n"); System.out.println("-----Display students------");
List<Student> studentList = studentDao.selectAllStudents();
for (int i = 0, length = studentList.size(); i < length; i++)
System.out.println(studentList.get(i));
}
}
由于StudentDaoImpl.java类使用了@Repository注解且没有指定别名,因此StudentDaoImpl.java在Spring容器中的名字为"首字母小写+剩余字母"即"studentDaoImpl"。
运行一下程序,可以看见控制台上遍历出了new出来的Student,即该Student直接被插入了数据库中,整个过程中没有任何的commit、rollback,全部都是由Spring帮助我们实现的,这就是利用Spring对MyBatis进行事务管理。
后记
本文复习了MyBatis的基本使用与使用Spring对MyBatis进行事务管理,给出了比较详细的代码例子,有需要的朋友们可以照着代码研究一下。在本文的基础上,后面还会写一篇文章,讲解一下多数据在单表和多表之间的事务管理实现,这种需求也是属于企业及应用中比较常见的需求。
MyBatis5:MyBatis集成Spring事物管理(上篇)的更多相关文章
- MyBatis6:MyBatis集成Spring事物管理(下篇)
前言 前一篇文章<MyBatis5:MyBatis集成Spring事物管理(上篇)>复习了MyBatis的基本使用以及使用Spring管理MyBatis的事物的做法,本文的目的是在这个的基 ...
- MyBatis6:MyBatis集成Spring事务管理(下篇)
前言 前一篇文章<MyBatis5:MyBatis集成Spring事务管理(上篇)>复习了MyBatis的基本使用以及使用Spring管理MyBatis的事务的做法,本文的目的是在这个的基 ...
- MyBatis5:MyBatis集成Spring事务管理(上篇)
前言 有些日子没写博客了,主要原因一个是工作,另一个就是健身,因为我们不仅需要努力工作,也需要有健康的身体嘛. 那有看LZ博客的网友朋友们放心,LZ博客还是会继续保持更新,只是最近两三个月LZ写博客相 ...
- 集成Spring事物管理
什么是事物 事物是访问数据库的一个操作序列,数据库应用系统通过事物集来完成对数据库的存取.事物的正确执行使得数据库从一种状态转换为另一种状态. 事物必须服从ISO/IEC所制定的ACID原则.ACID ...
- MyBatis(5):MyBatis集成Spring事务管理(上)
单独使用MyBatis对事务进行管理 前面MyBatis的文章有写过相关内容,这里继续写一个最简单的Demo,算是复习一下之前MyBatis的内容吧,先是建表,建立一个简单的Student表: 1 2 ...
- MyBatis(6):MyBatis集成Spring事务管理(下)
前一篇文章复习了MyBatis的基本使用以及使用Spring管理MyBatis的事务的做法,本文的目的是在这个的基础上稍微做一点点的进阶:多数据的事务处理.文章内容主要包含两方面: 1.单表多数据的事 ...
- Spring事物管理--相关要点及配置事物管理器
事务的四大特征 1.原子性:一个事务中所有对数据库的操作是一个不可分割的操作序列,要么全做要么全不做 2.一致性:数据不会因为事务的执行而遭到破坏 3.隔离性:一个事物的执行,不受其他事务的干扰,即并 ...
- spring 事物管理没起到作用
今天在做项目的时候发现配置的spring 事物管理没起到作用.可是配置又是依据官网配置的,不可能会错.最后发现使mysql的问题 普通情况下,mysql会默认提供多种存储引擎,你能够通过以下的查看: ...
- java陷阱之spring事物管理导致锁无效
模拟锁情况无效 1.创建一个表 SET NAMES utf8mb4; ; DROP TABLE IF EXISTS `demo`; CREATE TABLE `demo` ( `id` ) NOT N ...
随机推荐
- 学习AOP之认识一下Spring AOP
心碎之事 要说知道AOP这个词倒是很久很久以前了,但是直到今天我也不敢说非常的理解它,其中的各种概念即抽象又太拗口. 在几次面试中都被问及AOP,但是真的没有答上来,或者都在面上,这给面试官的感觉就是 ...
- SQL Server技术内幕笔记合集
SQL Server技术内幕笔记合集 发这一篇文章主要是方便大家找到我的笔记入口,方便大家o(∩_∩)o Microsoft SQL Server 6.5 技术内幕 笔记http://www.cnbl ...
- CENTOS 6.5 平台离线安装 Apache2.4
一.下载Apache 2.4 http://httpd.apache.org/download.cgi http://mirrors.cnnic.cn/apache//httpd/httpd-2.4. ...
- C++11特性——变量部分(using类型别名、constexpr常量表达式、auto类型推断、nullptr空指针等)
#include <iostream> using namespace std; int main() { using cullptr = const unsigned long long ...
- C#创建、安装、卸载、调试Windows Service(Windows 服务)的简单教程
前言:Microsoft Windows 服务能够创建在它们自己的 Windows 会话中可长时间运行的可执行应用程序.这些服务可以在计算机启动时自动启动,可以暂停和重新启动而且不显示任何用户界面.这 ...
- [WPF] Wait for a moment.
一.控件介绍 在 WPF 中使用的等待控件,控件包括三种,普通的等待信息提示(WaitTip),进度条提示(WaitProgress),以及主程序覆盖的模拟时钟等待窗口(WaitClock),具体效果 ...
- WPF 捕获键盘输入事件
最近修改的一个需求要求捕获键盘输入的 Text,包括各种标点符号. 最开始想到的是 PreviewKeyDown 或者 PreviewKeyUp 这样的键盘事件. 但是这两个事件的对象 KeyEven ...
- iOS10之Expected App Behaviors
昨天上架到appStore的时候碰到个问题,构建好后上传到itunesconnect的的包都用不了, 显示错误为:此构建版本无效. 或者英文显示为:ITC.apps.preReleaseBuild.e ...
- 烂泥:VMWare Workation双网卡配置IP地址
本文由ilanniweb提供友情赞助,首发于烂泥行天下 想要获得更多的文章,可以关注我的微信ilanniweb 前几天给一个客户做远程项目实施,客户那边的服务器是Windows OS的,我们这边的业务 ...
- Android Bitmap 和 ByteArray的互相转换
Android Bitmap 和 ByteArray的互相转换 移动平台图像处理,需要将图像传给native处理,如何传递?将bitmap转换成一个 byte[] 方便传递也方便cpp代码直接处理图像 ...