下面这段代码有什么问题吗?
为什么无法自动开启事务并提交?
spring想管理hibernate的事务,也就是通过这几行代码就可以了吧?
通过spring管理事务,执行后没有任何的效果,我觉得应该是事务没有提交的事
不过是否开启也不确定,如何能排查出问题原因呢?
<!-- spring接管事务 -->
<bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<!-- 事务增强 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="*"/>
</tx:attributes>
</tx:advice>
<!-- 使用aop自动开启/提交事务 -->
<aop:config>
<aop:pointcut expression="execution(* com.web.service.*.*(..))" id="serviceMethod"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="serviceMethod"/>
</aop:config>
原来的代码
Session session = sessionFactory.openSession();
现在的代码
Session session = sessionFactory.getCurrentSession();
用getCurrentSession可以开启事务,不知道为什么openSession不可以
在spring的配置文件里 只需要加入这个
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
然后在你的dao层,加上@Transactional,表示这个类接受事务管理,
package com.dao;
import javax.annotation.Resource;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.pojo.User;
@Repository("userDAO")
@Transactional
public class UserDAO {
@Resource
private SessionFactory sessionFactory;
private Session openSession() {
return sessionFactory.openSession();
}
public void insert(User user) {
openSession().save(user);
}
}