我有一个需要保存的 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
在同一个项目中,您更有可能遇到此问题。
您的代码应该是:
选项 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;
}
}
关于hibernate - 使用 Spring Hibernate 获取事务未成功启动异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7484890/