事务加在DAO层还是Service层?
service
使用
annotation
i.
加入annotation.xsd
ii.
加入txManager
bean
iii.
<tx:annotation-driven
iv.
在需要事务的方法上加:@Transactional
v.
需要注意,使用SessionFactory.getCurrentSession
不要使用OpenSession
@Transactional详解
什么时候rollback
运行期异常,非运行期异常不会触发rollback
必须uncheck
(没有catch)
不管什么异常,只要你catch了,spring就会放弃管理
事务传播特性:propagation_required 默认
当这个方法没有事务时,创建一个
当这个方法有事务时,用当前的
read_only
做查询时,Connection(只读)提高性能
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<context:annotation-config
/>
<context:component-scan
base-package="org.spring" />
<bean
id="txManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property
name="sessionFactory" ref="mySessionFactory" />
</bean>
<tx:annotation-driven
transaction-manager="txManager"/>
</beans>
UserService中: 保存User后,还需记录日志,两个方法放在一个事务中处理
@Transactional
public void add(User user) {
userDAO.save(user);
Log log = new
Log();
log.setMsg("a
user saved!");
logDAO.save(log);
}
加载中,请稍候......