0

我有一个方法:

package com.abc.pkg.service.db.impl;



public class OperationServiceImpl extends BaseService implements OperationService {



    @Transactional
        @Override
        public String update(Operation operation,User user) {

        BigDecimal count=(BigDecimal)em.createNativeQuery("select count(*) from RBMCORE.T_RBM_OPSCREENS_OPERATIONS where s_name= ? and id!= ?").setParameter(1, operation.getName()).setParameter(2, operation.getId()).getSingleResult();

        if(count.intValue()>0)
            return "This operation name is used by another operation. Please change it";

        super.removeOpAppRelation(operation.getId(), -1);

        Operation oldOperation=operationRepository.save(operation);
        List<Operation> operations=new ArrayList<Operation>();
        operations.add(operation);
}
}

而super.insertOpAppRelation方法内容为:

package com.abc.pkg.service.db.impl;
public abstract class BaseService {


@PersistenceContext
protected EntityManager em;

@Transactional
    protected  void removeOpAppRelation(int opId,int appId){
        String sql="delete table a where 1=1";
        if(opId>0)
            sql+=" and op_id="+opId;

        if(appId>0)
            sql+=" and app_id="+appId;

        em.createNativeQuery(sql).executeUpdate();
    }
}

并触发 removeOpAppRelation 方法,抛出此异常:

javax.persistence.TransactionRequiredException:执行更新/删除查询

在我的 appcontext.xml 我有这些:

<tx:annotation-driven transaction-manager="transactionManager"/>
<context:component-scan base-package="com.abc.pck"/>

<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="dataSource" ref="rbmDataSource"/>
    <property name="packagesToScan" value="com.ttech.rbm.model"/>
    <property name="jpaVendorAdapter">
        <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
            <property name="databasePlatform" value="org.hibernate.dialect.Oracle10gDialect"/>
            <property name="showSql" value="true"/>
            <property name="generateDdl" value="true"/>
        </bean>
    </property>
    <property name="jpaProperties">
        <props>
            <prop key="hibernate.hbm2ddl.auto">none</prop>
        </props>
    </property>
</bean>

<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
    <property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>

作为事务经理,我正在使用:

org.springframework.orm.jpa.JpaTransactionManager

有任何想法吗?跟继承有关系吗?

4

2 回答 2

0

找到了。我传递给事务管理器的实体管理器不是 AOP 安全的。因此,它在使用它执行查询时不会启动事务。我已经打开并管理了我自己的交易并且问题解决了。感谢您的回复

于 2013-09-09T06:08:06.053 回答
0

您的代码非常简化。

使用的“em”未在您的任何类中声明。

我会期待一个

@PersistenceContext
EntityManager em;

在你的一门课上。

如果它在两个类中,它将解释您的错误,因为在这种情况下,将注入两个不同的实体管理器,它们不会共享相同的事务。

为了避免这种情况,你应该在你的超类中使用一个抽象方法“getEm()”并在你的子类中覆盖它,提供在那里注入的em。

此外,父类上的@Transactional 在子类调用时将不起作用,因为它是直接从子类调用的超方法,而不是通过spring-aop-proxy - spring 没有机会拦截。

于 2013-09-05T21:02:40.163 回答