欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

MyBatis5中Spring集成MyBatis事物管理

 更新時間:2016年05月03日 12:06:26   作者:五月的倉頡  
這篇文章主要介紹了MyBatis5中MyBatis集成Spring事物管理的相關(guān)資料,需要的朋友可以參考下

單獨使用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)
)

建立實體類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()方法,打印其中每一個(或者說是關(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、定義和實現(xiàn)分開

2、分層開發(fā),通常情況下為Dao-->Service-->Controller,不排除根據(jù)具體情況多一層/幾層或少一層

所以,先寫一個StudentDao.java接口:

public interface StudentDao
{
public List<Student> selectAllStudents();
public int insertStudent(Student student);
}

最后寫一個StudentDaoImpl.java實現(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來實現(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的實現(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)點:見名知意,即看到這個注解就大致知道這個類的作用即它在整個項目中的定位。

(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"。

運行一下程序,可以看見控制臺上遍歷出了new出來的Student,即該Student直接被插入了數(shù)據(jù)庫中,整個過程中沒有任何的commit、rollback,全部都是由Spring幫助我們實現(xiàn)的,這就是利用Spring對MyBatis進(jìn)行事物管理。

后記

本文復(fù)習(xí)了MyBatis的基本使用與使用Spring對MyBatis進(jìn)行事物管理,給出了比較詳細(xì)的代碼例子,有需要的朋友們可以照著代碼研究一下。在本文的基礎(chǔ)上,后面還會寫一篇文章,講解一下多數(shù)據(jù)在單表和多表之間的事物管理實現(xiàn),這種需求也是屬于企業(yè)及應(yīng)用中比較常見的需求。

相關(guān)文章

  • Java實現(xiàn)向Word文檔添加文檔屬性

    Java實現(xiàn)向Word文檔添加文檔屬性

    這篇文章主要介紹了Java實現(xiàn)向Word文檔添加文檔屬性的相關(guān)資料,需要的朋友可以參考下
    2023-01-01
  • Java排序算法之選擇排序

    Java排序算法之選擇排序

    這篇文章主要介紹了Java排序算法之選擇排序,文中有非常詳細(xì)的代碼示例,對正在學(xué)習(xí)java的小伙伴們有非常好的幫助,需要的朋友可以參考下
    2021-05-05
  • 淺談java中異常拋出后代碼是否會繼續(xù)執(zhí)行

    淺談java中異常拋出后代碼是否會繼續(xù)執(zhí)行

    這篇文章主要給大家介紹了java中異常拋出后代碼是否會繼續(xù)執(zhí)行,文章通過幾種情況的代碼示例給大家詳細(xì)分析了這個情況,有需要的朋友們可以參考借鑒,下面來一起看看吧。
    2016-10-10
  • springboot的EnvironmentPostProcessor接口方法源碼解析

    springboot的EnvironmentPostProcessor接口方法源碼解析

    這篇文章主要介紹了springboot的EnvironmentPostProcessor接口方法源碼解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-08-08
  • Java中的比較器詳細(xì)解析

    Java中的比較器詳細(xì)解析

    這篇文章主要介紹了Java中的比較器詳細(xì)解析,基本數(shù)據(jù)類型的數(shù)據(jù)(除boolean類型外)需要比較大小的話,直接使用比較運算符即可,但是引用數(shù)據(jù)類型是不能直接使用比較運算符來比較大小的,需要的朋友可以參考下
    2023-11-11
  • Java責(zé)任鏈設(shè)計模式實例分析

    Java責(zé)任鏈設(shè)計模式實例分析

    這篇文章主要介紹了Java責(zé)任鏈設(shè)計模式,結(jié)合實例形式詳細(xì)分析了Java責(zé)任鏈設(shè)計模式的原理與相關(guān)操作技巧,需要的朋友可以參考下
    2019-07-07
  • java連接sql server 2008數(shù)據(jù)庫代碼

    java連接sql server 2008數(shù)據(jù)庫代碼

    Java的學(xué)習(xí),很重要的一點是對數(shù)據(jù)庫進(jìn)行操作。
    2013-03-03
  • 詳解SpringMVC實現(xiàn)圖片上傳以及該注意的小細(xì)節(jié)

    詳解SpringMVC實現(xiàn)圖片上傳以及該注意的小細(xì)節(jié)

    本篇文章主要介紹了詳解SpringMVC實現(xiàn)圖片上傳以及該注意的小細(xì)節(jié),具有一定的參考價值,感興趣的小伙伴們可以參考一下。
    2017-02-02
  • 淺析Java 并發(fā)編程中的synchronized

    淺析Java 并發(fā)編程中的synchronized

    這篇文章主要介紹了Java 并發(fā)編程中的synchronized的相關(guān)資料,幫助大家更好的理解和學(xué)習(xí)Java并發(fā)編程,感興趣的朋友可以了解下
    2020-12-12
  • 詳解spring項目中如何動態(tài)刷新bean

    詳解spring項目中如何動態(tài)刷新bean

    這篇文章主要為大家介紹了詳解spring項目中如何動態(tài)刷新bean,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-08-08

最新評論