MyBatis5:MyBatis整合Spring事務管理(上篇)

五月的倉頡發表於2016-05-03

前言

有些日子沒寫部落格了,主要原因一個是工作,另一個就是健身,因為我們不僅需要努力工作,也需要有健康的身體嘛。

那有看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類:

 1 public class StudentDaoImpl extends MyBatisUtil implements StudentDao
 2 {
 3     private static final String NAMESPACE = "StudentMapper.";
 4     
 5     public List<Student> selectAllStudents()
 6     {
 7         SqlSession ss = getSqlSession();
 8         List<Student> list = ss.selectList(NAMESPACE + "selectAllStudents");
 9         ss.close();
10         return list;
11     }
12 
13     public int insertStudent(Student student)
14     {
15         SqlSession ss = getSqlSession();
16         int i = ss.insert(NAMESPACE + "insertStudent", student);
17         // ss.commit();
18         ss.close();
19         return i;
20     }
21 }

寫一個測試類:

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進行事務管理,給出了比較詳細的程式碼例子,有需要的朋友們可以照著程式碼研究一下。在本文的基礎上,後面還會寫一篇文章,講解一下多資料在單表和多表之間的事務管理實現,這種需求也是屬於企業及應用中比較常見的需求。

相關文章