一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

服務器之家:專注于服務器技術及軟件下載分享
分類導航

PHP教程|ASP.NET教程|JAVA教程|ASP教程|

服務器之家 - 編程語言 - JAVA教程 - MyBatis5中Spring集成MyBatis事物管理

MyBatis5中Spring集成MyBatis事物管理

2020-04-24 12:21五月的倉頡 JAVA教程

這篇文章主要介紹了MyBatis5中MyBatis集成Spring事物管理的相關資料,需要的朋友可以參考下

單獨使用MyBatis對事物進行管理

前面MyBatis的文章有寫過相關內容,這里繼續寫一個最簡單的Demo,算是復習一下之前MyBatis的內容吧,先是建表,建立一個簡單的Student表:

?
1
2
3
4
5
6
create table student
(
student_id int auto_increment,
student_name varchar(20) not null,
primary key(student_id)
)

建立實體類Student.java:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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基本配置:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<?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語句:

?
1
2
3
4
5
6
7
8
9
10
11
12
<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基本元素的,后面的類都繼承這個類:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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接口:

?
1
2
3
4
5
public interface StudentDao
{
public List<Student> selectAllStudents();
public int insertStudent(Student student);
}

最后寫一個StudentDaoImpl.java實現這個接口,注意要繼承MyBatisUtil.java類:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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;
}
}

寫一個測試類:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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的部分:

?
1
2
3
4
5
6
7
8
<?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:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<?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,具體代碼如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@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并進行數據的增、刪、改、查了。

最后無非就是寫一個測試類測試一下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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進行事物管理,給出了比較詳細的代碼例子,有需要的朋友們可以照著代碼研究一下。在本文的基礎上,后面還會寫一篇文章,講解一下多數據在單表和多表之間的事物管理實現,這種需求也是屬于企業及應用中比較常見的需求。

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 免费看麻豆视频 | 18岁的老处女 | 亚洲色欧美图 | 四虎成人免费观看在线网址 | 亚洲精品国产自在现线最新 | www.91在线视频 | 久久久久久久久人体 | 深夜福利一区 | 国产成人www免费人成看片 | 爱爱调教 | 性吟网 | 美女在尿口隐私视频 | 青青草原在线免费 | 超级碰碰免费视频 | 911精品国产亚洲日本美国韩国 | 三级欧美在线 | 久久九九久精品国产尤物 | 性夜夜春夜夜爽AA片A | 国产第一综合另类色区奇米 | 国产一卡二卡3卡4卡更新 | 欧美国产日产精品免费视频 | 香蕉eeww99国产精选播放 | 国产精品视频第一区二区三区 | 王雨纯 羞羞 | 麻豆网 | 91制片厂制作果冻传媒八夷 | 韩国伦理hd | 青青青青在线视频 | 秋霞午夜伦午夜高清福利片 | 嗯啊在线观看免费影院 | 91亚洲精品丁香在线观看 | 欧美巨吊 | 午夜影院免费看 | 精品国产午夜久久久久九九 | 国产成人在线免费观看 | 哇嘎在线精品视频在线观看 | 国产rpg迷雾之风冷狐破解 | 成人免费视频一区二区三区 | 911亚洲精品国内自产 | 嫩草影院永久入口在线观看 | 天天做日日做天天添天天欢公交车 |