【发布时间】:2015-06-30 07:30:30
【问题描述】:
我想从使用 TransactionProxyFactoryBean 的旧式事务管理迁移到 spring 推荐的声明式事务管理。 这样就可以避免不时出现的交易异常。
这是我的配置xml文件:
<beans xmlns=...>
<context:annotation-config/>
<context:component-scan base-package="prof" />
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="configLocation">
<value>WEB-INF/classes/hibernate.cfg.xml</value>
</property>
</bean>
<import resource="prof-dao-spring.xml" />
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<bean id="baseTransactionProxy" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean" abstract="true">
<property name="transactionManager">
<ref bean="transactionManager"/>
</property>
<property name="transactionAttributes">
<props>
<prop key="save*">PROPAGATION_REQUIRED</prop>
...
<prop key="*">PROPAGATION_REQUIRED,readOnly</prop>
</props>
</property>
</bean>
<bean id="ProfileService" parent="baseTransactionProxy">
<property name="target">
<bean class="tv.clever.hibernate.service.ProfileService"></bean>
</property>
</bean>
</beans>
ProfileService 看起来像:
@Component
public class ProfileService {
@Autowired
@Qualifier("baseDAO")
protected BaseDAO baseDAO;
private static ProfileService profileService;
public ProfileService() {
setProfileService(this);
}
public void setProfileService(ProfileService ps) {
profileService = ps;
}
public void save(final Collection transientObjects) {
baseDAO.save(transientObjects);
}
...
}
我需要从哪里开始?
【问题讨论】:
-
你想做什么?使用注释,即
@Transactional?还是仍然使用 XML?小提示而不是@Component我建议使用@Service标记您的服务类并使用@Repository标记您的daos。为自己设置静态引用的装置是什么,这会让我的警钟响起……您当前的设置也在复制所有 bean?您有组件扫描和手动配置,基本上是为每个 bean 创建 2 个实例(不包括代理)。 -
是的,我想要一个像这个例子中的
Annotation style transaction(1.注解式事务):simplespringtutorial.com/springDeclarativeTransactions.html不同的是我使用的是Hibernate FrameworkHibernateTransactionManager -
哪个事务管理器无关紧要。
-
无论使用普通JDBC的JPA、Hibernate、JTA,无关事务管理的技术都是一样的。根本没关系,只需将正确的事务管理器连接到事务的东西,其余的都是一样的。这就是声明式事务管理的重点,无论您使用什么,它都保持不变。
标签: spring transactions