我有一个需要保存的UserProfile实体。将实体保存在数据库中后,出现以下异常:
Could not commit Hibernate transaction; nested exception is org.hibernate.TransactionException: Transaction not successfully started
另外,当我看到该表时,该实体将保留而不是进行回滚!
@Transactional(isolation=Isolation.REPEATABLE_READ) public class HibernateUserProfileDAO implements UserProfileDAO { private org.hibernate.SessionFactory sessionFactory; public UserProfile getUserProfile(int userId) { org.hibernate.classic.Session session = sessionFactory.getCurrentSession(); session.beginTransaction(); UserProfile userProfile = new UserProfile(); userProfile.setUserName("sury1"); session.save(userProfile); session.getTransaction().commit(); session.close(); return userProfile; } }
我正在使用hibernate事务管理器
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"/> </bean>
而我的hibernate配置是:
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <property name="packagesToScan" value="com.springheatmvn.domain"/> <property name="hibernateProperties"> <props> <prop key="hibernate.connection.pool_size">10</prop> <prop key="hibernate.connection.show_sql">true</prop> <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop> <prop key="hibernate.hbm2ddl.auto">update</prop> </props> </property> </bean>
任何人都可以。告诉我这是怎么回事?
我认为您已经成为双重交易管理的受害者。如果在同一项目中一起使用Spring Transaction Management和Hibernate Transaction Management在一起,则更可能出现此问题。
Spring Transaction Management
Hibernate Transaction Management
您的代码应为:
选项1. hibernate事务管理
public class HibernateUserProfileDAO implements UserProfileDAO { private org.hibernate.SessionFactory sessionFactory; public UserProfile getUserProfile(int userId) { org.hibernate.classic.Session session = sessionFactory.getCurrentSession(); session.beginTransaction(); UserProfile userProfile = new UserProfile(); userProfile.setUserName("sury1"); session.save(userProfile); session.getTransaction().commit(); session.close(); return userProfile; } }
或 选项2。 spring交易管理
@Transactional public class HibernateUserProfileDAO implements UserProfileDAO { private org.hibernate.SessionFactory sessionFactory; public UserProfile getUserProfile(int userId) { org.hibernate.classic.Session session = sessionFactory.getCurrentSession(); UserProfile userProfile = new UserProfile(); userProfile.setUserName("sury1"); session.save(userProfile); session.close(); return userProfile; } }