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

时间:2014-07-31 10:52:09

标签: spring-boot

我正在使用Spring Boot并按照以下方式配置我的应用程序:

@Configuration
@EnableAutoConfiguration
@EnableTransactionManagement
@ComponentScan
@EntityScan("ch.xy.model")
public class Application {

    @Autowired
    private ImportDAO importDao;

}

ImportDAO看起来像这样:

@Repository
public class ImportDAO {

    @PersistenceContext
    private EntityManager em;

    @Transactional
    void removeTempoAccounts() {
        Query q = em.createQuery("DELETE FROM TempoAccount t WHERE t.manual = false");
        q.executeUpdate();
    }
}

但是当执行removeTempoAcconts时,我得到:

线程“main”中的异常javax.persistence.TransactionRequiredException:执行更新/删除查询     在org.hibernate.jpa.spi.AbstractQueryImpl.executeUpdate(AbstractQueryImpl.java:71)     at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)     at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)     at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)     at java.lang.reflect.Method.invoke(Method.java:606)     在org.springframework.orm.jpa.SharedEntityManagerCreator $ DeferredQueryInvocationHandler.invoke(SharedEntityManagerCreator.java:360)     在com.sun.proxy。$ Proxy49.executeUpdate(未知来源)     at ch.post.pf.jira.tempocats.pspimport.ImportDAO.removeTempoAccounts(ImportDAO.java:95)     at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)     at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)     at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)     at java.lang.reflect.Method.invoke(Method.java:606)     在org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)     在org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)     在org.springframework.aop.framework.CglibAopProxy $ CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:711)     在org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)     在org.springframework.aop.framework.CglibAopProxy $ DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:644)     at ch.post.pf.jira.tempocats.pspimport.ImportDAO $$ EnhancerBySpringCGLIB $$ 1883cf82.removeTempoAccounts()     在ch.post.pf.jira.tempocats.pspimport.PspImport.run(PspImport.java:32)     at ch.post.pf.jira.tempocats.pspimport.Application.main(Application.java:20)

我的配置有什么问题?

2 个答案:

答案 0 :(得分:2)

@Transactional
void removeTempoAccounts() {

方法具有默认可见性。因此代理机制不活跃! 在按照预期更改为公共外部工作后!

答案 1 :(得分:1)

尝试使用Spring包中的@Transactional注释 像@org.springframework.transaction.annotation.Transactional 然后它应该工作