簡體   English   中英

CDI環境中的Spring-Data-JPA?

[英]Spring-Data-JPA in CDI environment?

有人嘗試過將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文件?

由於您位於Java EE應用程序容器中,因此您不想創建自己的Persistence實例。 您使用的Spring Data文檔中的示例適用於沒有內置JPA支持的CDI環境。 Glasfish為您創建EntityManagerFactoryEntityManager 您只需要將其重新發布為CDI bean。 因此,對於您而言,使用文檔中顯示的第二個示例很重要:

public class EntityManagerProducer {

    @Produces
    @RequestScoped
    @PersistenceContext
    private EntityManager entityManager;
}

官方文檔中所說的內容有些棘手。 為了在CDI環境中正確處理Spring Repository,您需要聲明:

  • 附屬實體經理制作人

     @Produces @Dependent @PersistenceContext EntityManager entityManager; 
  • 渴望的倉庫

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

然后,您可以@將存儲庫@Inject CDI托管Bean中。 如果不使用@Dependent@Eager批注,Spring將在存儲庫初始化時引發異常,從而導致針對它的第一個請求的未捕獲過期。

參考文獻:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM