这一篇,我们来介绍使用@Transactional注解进行事务管理。
首先,我们只要使用spring的事务管理,不论你使用xml配置文件的方式还是使用注解的方式,我们都需要先将spring关于事务管理的包导入项目:
其次,我们在进行编写有关的代码与配置。其实,使用@Transactional注解方式的事务管理与我们使用xml配置的大同小异,只需要更改下我们的applacation.xml文件中的相关配置信息就好。
下面贴上application.xml的代码:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
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/jee http://www.springframework.org/schema/jee/spring-jee-4.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd">
<!-- 定义session工厂 -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<!-- 注入连接池,包含了数据库用户名,密码等等信息 -->
<property name="dataSource" ref="myDataSource" />
<!-- 配置Hibernate的其他的属性 -->
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.connection.autocommit">false</prop>
<!-- 开机自动生成表 -->
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
<property name="mappingResources">
<list>
<value>news/entity/News.hbm.xml</value>
</list>
</property>
</bean>
<!-- 同样先声明一个Spring事务管理者,名字为默认值(不可更改) -->
<bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<!--替代tx/aop命名空间-->
<tx:annotation-driven transaction-manager="transactionManager"/>
以上便是我们使用注解方式事务管理的application.xml文件编写,与使用xml配置方式便是 使用<tx:annotation-driven>替代了<tx:advice>/<aop:config>。
配置完application.xml文件后,我们便可以在service层中使用注解@Transactional来使用事务了。而且,我们可以将@Transactional添加在我们service层中的接口、接口中的方法、类以及类方法上。
一般,我们会直接将它添加到我们的类上,而不添加在接口上,因为只有基于接口的代理中它才会生效。
下面,我们贴上service层中的代码:
//使用在类上的注解
@Transactional
public class NewsServiceImpl implements NewsService {
//也可以添加在我们的方法上,并且为这个方法定义事务特性
@Transactional(readOnly=true)
public List showAllNews() {
List<News> allNewList = nd.showAllNews();
return allNewList;
}
}现在基于spring声明式管理的xml配置方式以及注解 两种方式进行简单的总结:
在我看来,我个人认为xml配置 方式的事务管理比较繁琐,但是却具有良好的观看性,当别的程序员观看你的代码时,可以比较好理解所写的配置信息。
而注解 方式就可以比较方便代码编写,比如在application.xml配置文件中的配置信息较少,并且使用时比较灵活,可以在我们想要添加的类或方法上任意添加。
以上观点为本人的微薄认知,如果读者对spring声明式事务管理有着更好、更加独特的观点,认知 都可以在下方进行评论告知。