【问题标题】:Spring-Data-JPA in CDI environment?CDI环境中的Spring-Data-JPA?
【发布时间】:2015-01-14 09:40:21
【问题描述】:

有人尝试将 spring-data-jpa 与 java-ee 应用程序集成吗? 我使用 glassfish3 作为应用程序容器。

我按照官方 spring-data-jpa 教程创建了一个类:

public class EntityManagerFactoryProducer {

    @Produces
    @ApplicationScoped
    public EntityManagerFactory createEntityManagerFactory() {
        return Persistence.createEntityManagerFactory("myPU");
    }

    public void close(@Disposes EntityManagerFactory entityManagerFactory) {
        entityManagerFactory.close();
    }

    @Produces
    @RequestScoped
    public EntityManager createEntityManager(EntityManagerFactory entityManagerFactory) {
        return entityManagerFactory.createEntityManager();
    }

    public void close(@Disposes EntityManager entityManager) {
        entityManager.close();
    }
}

但是当我尝试部署我的应用程序时,我遇到了一个异常:

Error occurred during deployment: Exception while preparing the app : Could not resolve a persistence unit corresponding to the persistence-context-ref-name [org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean/entityManager] in the scope of the module called [App]. Please verify your application.. Please see server.log for more details.
Command deploy failed.

我错过了什么?我还应该有另一个配置文件还是一些 xml 文件?

【问题讨论】:

  • 我认为问题可能在于您没有在 persistence.xml 中声明的名称为“myPU”的持久性单元。但我也不认为这是正确的做法。详情见我的回答。
  • PU 声明正确。

标签: java jakarta-ee cdi glassfish-3 spring-data-jpa


【解决方案1】:

这比官方文档中所说的要复杂一些。要在 CDI 环境中正确处理 Spring 存储库,您需要声明:

  • 依赖实体管理器生产者

    @Produces @Dependent @PersistenceContext 
    EntityManager entityManager;
    
  • 一个急切的存储库

    @Eager public interface TestRepository extends CrudRepository<TestEntity, Long>
    

然后您将能够@Inject CDI 托管 Bean 中的存储库。 如果不使用@Dependent@Eager 注解,Spring 将在初始化存储库时引发异常,从而导致针对它的第一个请求出现未捕获异常。

参考资料:

【讨论】:

  • @Dependent 伪作用域的问题是每个注入点将创建多个 entityManager(因此也是每个请求)
  • 在我的情况下,我使用了@Dependent,但没有使用@Eager 注释并且它有效。我使用的是 Wildfly,但不是 Glassfish。
  • 我不再做这个了,它可能在过去 4 年里发生了变化 :)
【解决方案2】:

由于您在 Java EE 应用程序容器中,因此您不想创建自己的 Persistence 实例。您使用的 Spring Data 文档中的示例适用于没有内置 JPA 支持的 CDI 环境。 Glasfish 为您创建EntityManagerFactoryEntityManager。您只需将其重新发布为 CDI bean。因此,在您的情况下,使用文档中显示的第二个示例很重要:

public class EntityManagerProducer {

    @Produces
    @RequestScoped
    @PersistenceContext
    private EntityManager entityManager;
}

【讨论】:

  • 据我记得,我试过了,但没用。不过我会再试一次,谢谢。
猜你喜欢
  • 2013-05-05
  • 1970-01-01
  • 2017-02-21
  • 1970-01-01
  • 1970-01-01
  • 2018-05-11
  • 1970-01-01
  • 1970-01-01
  • 2017-11-29
相关资源
最近更新 更多