当前位置: 首页 > 知识库问答 >
问题:

TransactionRequiredException:Spring5中没有正在进行的事务

桑宇
2023-03-14

我正在Spring3和Hibernate3中进行产品构建,我已经更新了这个Hibernate5和Spring5。现在我可以部署应用程序了,但是当我尝试与数据库连接时,会得到“javax.persistence.TransactionRequiredException:no transaction is in progress”

<bean id="sessionFactoryBean"
    class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
    <property name="dataSource" ref="dataSourceBean" />
    <property name="annotatedClasses">          
        <!-- The model class is incorporated here -->
        <list>               
             <value>com.test.ab.base.AaUser</value>
             <value>com.test.ab.dealer.AaDealer</value>
           <list>

<bean id="txManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
    <property name="sessionFactory" ref="sessionFactoryBean" />
</bean>
public class DatabaseConnection extends HibernateDaoSupport {

    public DatabaseConnection (){

    }

    public static String QUERY_PREFIX_COUNT = "SELECT COUNT(*) ";

    protected void applyNamedParameterToQuery(Query queryObject, String paramName, Object value)
            throws HibernateException {

        if (value instanceof Collection) {
            queryObject.setParameterList(paramName, (Collection) value);
        }
        else if (value instanceof Object[]) {
            queryObject.setParameterList(paramName, (Object[]) value);
        }
        else {
            queryObject.setParameter(paramName, value);
        }
    }

    protected String save(Object obj) throws HibernateException {
        return getHibernateTemplate().save(obj).toString();
    }

    protected void update(Object obj) throws HibernateException {
        getHibernateTemplate().update(obj);
    }

    //this is to be used to attached the detached object in session...
    protected void merge(Object obj) throws HibernateException {
        getHibernateTemplate().merge(obj);
    }

    protected void saveOrUpdObj(Object obj) throws HibernateException {
        getHibernateTemplate().saveOrUpdate(obj);
    }
}

共有1个答案

黄俊雄
2023-03-14

您错过了txManager的依赖项注入数据源,因此bean条目应如下所示

<bean id="txManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
    <property name="dataSource" ref="dataSource"/>
    <property name="sessionFactory" ref="sessionFactoryBean" />
</bean>
 类似资料: