簡體   English   中英

JPA / Hibernate動態注入實體管理器

[英]JPA/Hibernate dynamically injecting entity manager

我有一個帶有多個實體管理器的JPA /休眠設置。 我想要做的是將實體管理器動態地注入具有相同實體定義的多個模式所使用的抽象類中-這些表在單個MySQL服務器中的不同數據庫中完全相同。 我試圖不編寫不必要的重復代碼,但似乎無法找到一種無需重復大量代碼即可動態注入持久性上下文的方法。 有什么辦法嗎?

那么,您是否需要更改 DAO實例中存在的EntityManager? 如果是,我想說的只是切換您的連接池。

相反,如果您要選擇連接到哪個實例,請在一個或多個配置文件中設置必要的鍵,然后使用該鍵為您的連接池獲取必要的連接屬性。

如果要具有同一個DAO的多個實例,請使用合格的bean和構造函數注入為它們提供適當的實體管理器(將工廠/池創建等其他所有內容抽象為方法)。

我最終創建了一個包含所有基本列表,更新,刪除方法的抽象DAO,並通過另一個抽象DAO進行了擴展,在其中我為該特定集合設置了實體管理器。 任何擴展最后一個DAO的DAO都將具有與之關聯的正確的帶注釋的實體管理器。 從那時起,我可以重用我的模型,而我要做的就是在服務層上擴展正確的DAO。

魔術通過使用@PerisstenceContext和持久性unitName調用setEntityManager(EntityManager em)來實現。 我不完全確定為什么這樣做,但似乎可以解決問題。

這是我所做的:AbstractJpaDao:

@MappedSuperclass
public class AbstractJpaDao <T>{
    private Class<T> clazz;
    protected EntityManager entityManager;

    public final void setClazz(final Class<T> clazzToSet) {
        this.clazz = clazzToSet;
    }

    @Transactional
    public T getById(final long id) {
        return entityManager.find(clazz, id);
    }
    //... all the others ...
}

InheritedDao1:

@MappedSuperclass
public class InheritedDao <T> extends AbstractJpaDao <T>{
    //This is what allows me to inject the entityManager by its annotation
    @PersistenceContext(unitName = "myPU")
    public void setEntityManager(EntityManager entityManager) {
        this.entityManager = entityManager;
    }
}

InheritedDao2:

@MappedSuperclass
public class OtherInheritedDao <T> extends AbstractJpaDao <T>{
    //This is what allows me to inject the entityManager by its annotation
    @PersistenceContext(unitName = "otherPU")
    public void setEntityManager(EntityManager entityManager) {
        this.entityManager = entityManager;
    }
}

服務1:

@Service
@Transactional(readOnly = true)
public class MyService extends InheritedDao<MyModel> {
    public MyService() {
        setClazz(MyModel.class);
    }
}

服務2:

@Service
@Transactional(readOnly = true)
public class OtherService extends OtherInheritedDao<MyModel> {
    public OtherService() {
        //same model as used in MyService
        setClazz(MyModel.class);
    }
}

暫無
暫無

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

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