MyBatis5中Spring集成MyBatis事物管理
單獨(dú)使用MyBatis對事物進(jìn)行管理
前面MyBatis的文章有寫過相關(guān)內(nèi)容,這里繼續(xù)寫一個最簡單的Demo,算是復(fù)習(xí)一下之前MyBatis的內(nèi)容吧,先是建表,建立一個簡單的Student表:
create table student ( student_id int auto_increment, student_name varchar(20) not null, primary key(student_id) )
建立實(shí)體類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 + "]}";
}
}
多說一句,對實(shí)體類重寫toString()方法,打印其中每一個(或者說是關(guān)鍵屬性)是一個推薦的做法。接著是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();
}
}
企業(yè)級開發(fā)講求:
1、定義和實(shí)現(xiàn)分開
2、分層開發(fā),通常情況下為Dao-->Service-->Controller,不排除根據(jù)具體情況多一層/幾層或少一層
所以,先寫一個StudentDao.java接口:
public interface StudentDao
{
public List<Student> selectAllStudents();
public int insertStudent(Student student);
}
最后寫一個StudentDaoImpl.java實(shí)現(xiàn)這個接口,注意要繼承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));
}
}
結(jié)果一定是空。
我說過這個例子既是作為復(fù)習(xí),也是作為一個引子引入我們今天的內(nèi)容,空的原因是,insert操作已經(jīng)做了,但是MyBatis并不會幫我們自動提交事物,所以展示出來的自然是空的。這種時候就必須手動通過SqlSession的commit()方法提交事務(wù),即打開StudentDaoImpl.java類第17行的注釋就可以了。
多說一句,這個例子除了基本的MyBatis插入操作之外,在插入的基礎(chǔ)上還有返回插入的主鍵id的功能。
接下來,就利用Spring管理MyBatis事物,這也是企業(yè)級開發(fā)中最常用的事物管理做法。
使用Spring管理MyBatis事物
關(guān)于這塊,網(wǎng)上有很多文章講解,我搜索了很多,但是要么就是相互復(fù)制黏貼,要么就是沒有把整個例子講清楚的,通過這一部分,我盡量講清楚如何使用Spring管理MyBatis事物。
使用Spring管理MyBatis事物,除了Spring必要的模塊beans、context、core、expression、commons-logging之外,還需要以下內(nèi)容:
(1)MyBatis-Spring-1.x.0.jar,這個是Spring集成MyBatis必要的jar包
(2)數(shù)據(jù)庫連接池,dbcp、c3p0都可以使用,我這里使用的是阿里的druid
(3)jdbc、tx、aop,jdbc是基本的不多說,用到tx和aop是因為Spring對MyBatis事物管理的支持是通過aop來實(shí)現(xiàn)的
(4)aopalliance.jar,這個是使用Spring AOP必要的一個jar包
上面的jar包會使用Maven的可以使用Maven下載,沒用過Maven的可以去CSDN上下載,一搜索就有的。
MyBatis的配置文件config.xml里面,關(guān)于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" /> <!-- 數(shù)據(jù)庫連接池,這里使用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> <!-- 事務(wù)管理器 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> </beans>
這里面主要就是事務(wù)管理器和數(shù)據(jù)庫連接池兩部分的內(nèi)容。
另外我們看到有一個SqlSessionFactory,使用過MyBatis的朋友們一定對這個類不陌生,它是用于配置MyBatis環(huán)境的,SqlSessionFactory里面有兩個屬性configLocation、mapperLocations,顧名思義分別代表配置文件的位置和映射文件的位置,這里只要路徑配置正確,Spring便會自動去加載這兩個配置文件了。
然后要修改的是Dao的實(shí)現(xiàn)類,此時不再繼承之前的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。它們的區(qū)別到不在于具體的語義上,更多的是在于注解的定位上。之前說過,企業(yè)級應(yīng)用注重分層開發(fā)的概念,因此,對這四個相似的注解應(yīng)當(dāng)有以下的理解:
•@Repository注解,對應(yīng)的是持久層即Dao層,其作用是直接和數(shù)據(jù)庫交互,通常來說一個方法對應(yīng)一條具體的Sql語句
•@Service注解,對應(yīng)的是服務(wù)層即Service層,其作用是對單條/多條Sql語句進(jìn)行組合處理,當(dāng)然如果簡單的話就直接調(diào)用Dao層的某個方法了
•@Controller注解,對應(yīng)的是控制層即MVC設(shè)計模式中的控制層,其作用是接收用戶請求,根據(jù)請求調(diào)用不同的Service取數(shù)據(jù),并根據(jù)需求對數(shù)據(jù)進(jìn)行組合、包裝返回給前端
•@Component注解,這個更多對應(yīng)的是一個組件的概念,如果一個Bean不知道屬于拿個層,可以使用@Component注解標(biāo)注
這也體現(xiàn)了注解的其中一個優(yōu)點(diǎn):見名知意,即看到這個注解就大致知道這個類的作用即它在整個項目中的定位。
(2)@Resource,這個注解和@Autowired注解是一個意思,都可以自動注入屬性屬性。由于SqlSessionFactory是MyBatis的核心,它在spring.xml中又進(jìn)行過了聲明,因此這里通過@Resource注解將id為"sqlSessionFactory"的Bean給注入進(jìn)來,之后就可以通過getSqlSession()方法獲取到SqlSession并進(jìn)行數(shù)據(jù)的增、刪、改、查了。
最后無非就是寫一個測試類測試一下:
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"。
運(yùn)行一下程序,可以看見控制臺上遍歷出了new出來的Student,即該Student直接被插入了數(shù)據(jù)庫中,整個過程中沒有任何的commit、rollback,全部都是由Spring幫助我們實(shí)現(xiàn)的,這就是利用Spring對MyBatis進(jìn)行事物管理。
后記
本文復(fù)習(xí)了MyBatis的基本使用與使用Spring對MyBatis進(jìn)行事物管理,給出了比較詳細(xì)的代碼例子,有需要的朋友們可以照著代碼研究一下。在本文的基礎(chǔ)上,后面還會寫一篇文章,講解一下多數(shù)據(jù)在單表和多表之間的事物管理實(shí)現(xiàn),這種需求也是屬于企業(yè)及應(yīng)用中比較常見的需求。
相關(guān)文章
Java基于IDEA實(shí)現(xiàn)qq郵件發(fā)送小程序
這篇文章主要介紹了Java基于IDEA實(shí)現(xiàn)qq郵件發(fā)送小程序功能,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-09-09
Java隊列同步器之CountDownLatch實(shí)現(xiàn)詳解
這篇文章主要介紹了Java隊列同步器之CountDownLatch實(shí)現(xiàn)詳解,CountDownLatch是一個同步工具類,它允許一個或多個線程一直等待,直到其他線程執(zhí)行完后再執(zhí)行,例如,應(yīng)用程序的主線程希望在負(fù)責(zé)啟動框架服務(wù)的線程已經(jīng)啟動所有框架服務(wù)之后執(zhí)行,需要的朋友可以參考下2023-12-12
java實(shí)體對象與Map之間的轉(zhuǎn)換工具類代碼實(shí)例
這篇文章主要介紹了java實(shí)體對象與Map之間的轉(zhuǎn)換工具類代碼實(shí)例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2019-12-12
關(guān)于break和continue以及l(fā)abel的區(qū)別和作用(詳解)
下面小編就為大家?guī)硪黄P(guān)于break和continue以及l(fā)abel的區(qū)別和作用(詳解)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-05-05
java中Webclient對象如何解析400狀態(tài)碼詳解
這篇文章主要介紹了java中Webclient對象如何解析400狀態(tài)碼的相關(guān)資料,文中通過代碼介紹的非常詳細(xì),對大家學(xué)習(xí)或者使用java具有一定的參考借鑒價值,需要的朋友可以參考下2024-12-12
Java中Spring技巧之?dāng)U展點(diǎn)的應(yīng)用
這篇文章主要介紹了Java中Spring技巧之?dāng)U展點(diǎn)的應(yīng)用,下文Spring容器的啟動流程圖展開其內(nèi)容的相關(guān)資料,具有一定的參考價值,需要的小伙伴可以參考一下2022-04-04

