我有一个带有多个实体管理器的JPA/hibernate设置。我想要做的是在一个抽象类中动态地注入实体管理器,该抽象类由多个模式使用,具有相同的实体定义--这些表在单个MySQL服务器中的不同数据库中完全相同。我试图避免编写不必要的重复代码,但我似乎无法找到一种在不重复大量代码的情况下动态注入持久性上下文的方法。有办法这样做吗?
发布于 2015-12-21 18:45:28
最后,我创建了一个包含所有基本列表、更新、删除方法的抽象DAO,并通过另一个抽象DAO进行扩展,在该抽象DAO中,我为该特定集合设置了实体管理器。任何扩展最后一个DAO的DAO都将与它们关联正确的带注释的实体管理器。从那时起,我就可以重用我的模型了,我所要做的就是在我的服务层上扩展正确的DAO。
通过使用@PerisstenceContext和持久性setEntityManager调用EntityManager(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;
}
}Service1:
@Service
@Transactional(readOnly = true)
public class MyService extends InheritedDao<MyModel> {
public MyService() {
setClazz(MyModel.class);
}
}Service2:
@Service
@Transactional(readOnly = true)
public class OtherService extends OtherInheritedDao<MyModel> {
public OtherService() {
//same model as used in MyService
setClazz(MyModel.class);
}
}发布于 2015-12-17 21:39:05
那么,您需要更改DAO实例中存在的EntityManager吗?如果是的话,我想换个连接池就行了。
如果您想要选择要连接到哪个实例,请在一个或多个配置文件中设置必要的键,然后使用该键获取连接池的必要连接属性。
如果您想拥有同一个DAO的多个实例,可以使用限定bean和构造函数注入来获得适当的实体管理器(将工厂/池创建之类的其他一切抽象为方法)。
https://stackoverflow.com/questions/34342211
复制相似问题