一尘不染

使用Spring Hibernate获取事务未成功启动的异常

hibernate

我有一个需要保存的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>

任何人都可以。告诉我这是怎么回事?


阅读 260

收藏
2020-06-20

共1个答案

一尘不染

我认为您已经成为双重交易管理的受害者。如果在同一项目中一起使用Spring Transaction ManagementHibernate 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;
    }
}
2020-06-20