【发布时间】: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