Spring整合Hibernate事务简单应用。文章简单介绍两种事务的使用,一是Spring注解的声明式事务,另一个是编程式事务。
在Spring中配置注解声明式事务,配置如下
<?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: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.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <!-- 使用spring注解 --> <!-- <context:annotation-config/> --> <!-- 下面的配置告诉spring容器自动scanner用注解标注bean --> <context:component-scan base-package="org.lian"/> <!--配置数据源 --> <!-- <bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${jdbc.driverClassName}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </bean> --> <!-- 配置Druid数据库连接池 --> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <!-- 基本属性 url、user、password --> <property name="driverClassName" value="${jdbc.driverClassName}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> <!-- 配置初始化大小、最小、最大 --> <property name="initialSize" value="1" /> <property name="minIdle" value="1" /> <property name="maxActive" value="20" /> <!-- 配置获取连接等待超时的时间 --> <property name="maxWait" value="60000" /> <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 --> <property name="timeBetweenEvictionRunsMillis" value="60000" /> <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 --> <property name="minEvictableIdleTimeMillis" value="300000" /> <property name="validationQuery" value="SELECT 'x'" /> <property name="testWhileIdle" value="true" /> <property name="testOnBorrow" value="false" /> <property name="testOnReturn" value="false" /> <!-- 打开PSCache,并且指定每个连接上PSCache的大小 --> <property name="poolPreparedStatements" value="true" /> <property name="maxPoolPreparedStatementPerConnectionSize" value="20" /> <!-- 配置监控统计拦截的filters,去掉后监控界面sql无法统计 --> <property name="filters" value="stat" /> </bean> <!-- 配置Hibernate SessionFactory --> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" lazy-init="false"> <!-- 注入datasource,给sessionfactoryBean内setdatasource提供数据源 --> <property name="dataSource" ref="dataSource"/> <property name="configLocation" value="classpath:conf/hibernate/hibernate.cfg.xml"></property> <!-- //加载实体类的映射文件位置及名称 --> <property name="mappingLocations" value="classpath:conf/hibernate/domain/*.hbm.xml"></property> <property name="packagesToScan" value="org.lian.**.domain"></property> </bean> <context:property-placeholder location="classpath*:conf/datasource/jdbc.properties"/> <!-- 采用注解的方式 声明事务 --> <tx:annotation-driven transaction-manager="txManager"/> <bean id="txManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"/> </bean> <!-- <aop:config> <aop:pointcut id="businessMethods" expression="execution(* org.lian.business.*Business.*(..))"/> <aop:advisor advice-ref="txAdvice" pointcut-ref="businessMethods"/> </aop:config> <tx:advice id="txAdvice" transaction-manager="txManager"> <tx:attributes> <tx:method name="addMusic*" propagation="REQUIRED"/> <tx:method name="editMusic*" propagation="REQUIRES_NEW"/> <tx:method name="*" propagation="SUPPORTS" read-only="true"/> </tx:attributes> </tx:advice> --> </beans>
使用Hibernate事务,获取session的方式有要求,强烈推荐使用下面的方式getCurrentSession(),openSession()方式实验了几次事务无法正常回滚。dao层的代码
@Repository("musicH4Dao")
public class MusicH4DaoImpl implements MusicDao {
@Autowired
private SessionFactory sessionFactory;
@Override
public void update(Music music) {
Session session = sessionFactory.getCurrentSession();
session
.createQuery(
"update Music as music set music.name=:name where music.id=:id ")
.setParameter("name", music.getName())
.setParameter("id", music.getId()).executeUpdate();
}
@Override
public void add(Music music) {
Session session = sessionFactory.getCurrentSession();
session.save(music);
session.flush();
}
}
业务层处理事务有两种方式,一种是声明式事务
@Service("musicBusiness")
@Transactional(readOnly = true)
public class MusicBusinessImpl implements MusicBusiness {
@Autowired
@Qualifier("musicH4Dao")
private MusicDao musicDao;
@Override
@Transactional(readOnly = false, rollbackFor = { Exception.class })
public void addMusic(Music music) {
musicDao.add(music);
Music bean = new Music();
bean.setId("123");
bean.setName("测试" + IdGenerator.getInstance().getUUID());
musicDao.update(bean);
}
}
另一种采用编程式事务处理
@Service("music2Business")
public class Music2BussinessImpl implements MusicBusiness {
private TransactionTemplate transactionTemplate;
@Qualifier("txManager")
@Autowired
public void setTransactionManager(
PlatformTransactionManager transactionManager) {
this.transactionTemplate = new TransactionTemplate(transactionManager);
}
@Autowired
@Qualifier("musicH4Dao")
private MusicDao musicDao;
@Override
public void addMusic(final Music music) {
// TODO Auto-generated method stub
this.transactionTemplate.execute(new TransactionCallbackWithoutResult() {
public void doInTransactionWithoutResult(TransactionStatus status) {
musicDao.add(music);
Music bean = new Music();
// music.setName("测试");
bean.setId("123");
bean.setName("测试" + IdGenerator.getInstance().getUUID());
musicDao.update(bean);
}
});
/*
* transactionTemplate.execute(new TransactionCallback<String>() { // the
* code in this method executes in a transactional context public String
* doInTransaction(TransactionStatus status) { return null; } });
*/
}
}