Spring中的@Transactional仅适用于只读但不能写入

时间:2018-11-22 01:35:28

标签: spring spring-orm

以前,我曾经明确地开始和提交事务,但是现在我试图在春季使用@Transactional注释。由于某些原因,所有只读操作都可以正常工作,但是persist()merge()操作无法工作,并且我在日志中看不到任何内容。在调试时,我还看到弹簧已经创建了代理,但不确定我要去哪里。这是我的代码和spring应用程序上下文配置。

1.Jpa-context.xml

<context:annotation-config />

<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="persistenceUnitName" value="PersistenceUnit" />
</bean>


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

<tx:annotation-driven proxy-target-class="true" transaction-manager="transactionManager" />

2.Framework-context.xml

<context:component-scan base-package="com.github.djuloori.whiteboard.framework" />
<context:annotation-config/>
<tx:annotation-driven proxy-target-class="true" transaction-manager="transactionManager" />
<bean id = "m_SecurableEntityManager"  class = "com.github.djuloori.whiteboard.framework.SecurableEntityManagerImpl"/>

3.SecurableEntityManagerImpl.Java

@Service
@Transactional
public class SecurableEntityManagerImpl implements SecurableEntityManager  {

    @Autowired
    private EntityManagerFactory entityManagerFactory;

    public void save(Object var1) {
        getEntityManager().persist(var1);
    }

    public <T> TypedQuery<T> createQuery(String var1, Class<T> var2) {
        return getEntityManager().createNamedQuery(var1,var2);
    }

    public <T> T update(T var1) {
        return getEntityManager().merge(var1);
    }


    private EntityManager getEntityManager(){
        return entityManagerFactory.createEntityManager();
    }
}

我还在阅读与@transactional相关的其他问题,但是找不到合适的答案。我是春天的新手,如果有人可以帮助我,那就太好了。

1 个答案:

答案 0 :(得分:0)

自动装配EntityManager解决了该问题