程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> 關於JAVA >> MyBatis5中Spring集成MyBatis事物治理

MyBatis5中Spring集成MyBatis事物治理

編輯:關於JAVA

MyBatis5中Spring集成MyBatis事物治理。本站提示廣大學習愛好者:(MyBatis5中Spring集成MyBatis事物治理)文章只能為提供參考,不一定能成為您想要的結果。以下是MyBatis5中Spring集成MyBatis事物治理正文


零丁應用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停止事物治理,給出了比擬具體的代碼例子,有須要的同伙們可以照著代碼研討一下。在本文的基本上,前面還會寫一篇文章,講授一下多半據在單表和多表之間的事物治理完成,這類需求也是屬於企業及運用中比擬罕見的需求。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved