【问题标题】:No transactional EntityManager available;没有可用的事务性EntityManager;
【发布时间】:2015-04-02 07:46:41
【问题描述】:

我的应用使用 spring 和 jpa,我有两个配置文件:

应用配置:

@Configuration
@EnableTransactionManagement
@ComponentScan(basePackages = { "com.test.api" })
@EnableJpaRepositories("com.test.api.repository")
@PropertySource("classpath:application.properties")
public class AppConfig { 
}

WebAppConfig:

@Configuration
  @EnableWebMvc
  @ComponentScan(basePackages = { "com.test.webservice" })
  public static class WebAppConfig extends WebMvcConfigurerAdapter {

  }

几乎可以正常工作,但有时它会抛出异常:Caused by: java.lang.IllegalStateException: No transactional EntityManager available 即使我只是选择记录(不创建、更新或删除数据。)

如果我将注释:@ComponentScan(basePackages = { "com.test.api" }) 移动到 Class WebAppConfig 并删除:@ComponentScan(basePackages = { "com.test.webservice" }),则异常消失,但是当服务器启动和 spring bean 重复时,spring 上下文加载很多次。

或者如果我使用entityManager.getEntityManagerFactory().createEntityManager().unwrap(Session.class) 代替entityManager.unwrap(Session.class),那么异常也会消失。

我该如何解决?

【问题讨论】:

    标签: spring entitymanager


    【解决方案1】:

    删除 WebAppConfig 上的 ComponentScan 并将包添加到 AppConfig 上的 ComponentScan 注释中,这应该可以解决您的问题。

    【讨论】:

    • 您能否发布您的代码,在哪里配置 EntityManager?可能有错误。
    猜你喜欢
    • 2013-01-06
    • 2013-01-09
    • 1970-01-01
    • 2015-01-31
    • 1970-01-01
    • 1970-01-01
    • 2015-09-16
    • 2019-01-20
    • 1970-01-01
    相关资源
    最近更新 更多