2016-11-09 61 views
2

我需要增加一点点智慧的JPA EntityManager的,定制createNamedQuery。 我正在构建许多模块的项目,其中每个模块使用@PersistenceContext(unitName = "emModuleName")注释其EntityManager的实例。自定义一个EntityManager

看来,我不能简单地扩展了接口EntityManager的,但我没有在网上找到有关此事的任何文件。

有没有人有一个想法什么是我的需求的最佳解决方案?

我不能延长一个具体实现,因为该应用程序必须是独立的JPA实现。 谢谢

+0

由于每个JPA提供者实现的EntityManager与自己的阶级,既然你说你不能扩展的实现,那么你就不能这样做。 –

回答

1

一种方法是创建自己的实现EntityManager,将作为真正的EnityManager包装。拦截所需的方法(在你的情况下为createNamedQuery),并将其他所有呼叫委托给解除对象。

创建您自己的代理拦截方法调用。然而

这两种方式都不是微不足道的使用,你可能会喜欢它的人。

0

您可以创建一个BaseEntitymanager它提供了基本的CRUD服务和相应的DAO具有延长BaseEntityManager基实现。

BaseEntityManager:

public interface EntityManagerBase<E, K> { 
    E create(E entity); 
    void delete(E entity); 
    E update(E entity); 
} 

EntityManagerBaseImpl

public abstract class EntityManagerBaseImpl<E, K> implements 
     EntityManagerBase<E, K> { 

    private EntityManager entityManager; 

    private TransactionManager txManager; 

    private Class<E> type; 

    public E create(E entity) {  
     entityManager.persist(entity); 
     entityManager.flush(); 
     return entity; 
    } 

MyDaoImpl:

public class MyDaoImpl extends EntityManagerBaseImpl<MyDBO, Long> implements MyDao { 
//put your implementation of methods 
}