简体   繁体   English

如何使用JPA /休眠EntityManager和EJB3.0实现泛型?

[英]How to implement generics using JPA/hibernate EntityManager and EJB3.0?

I have an slsb holding my business logic, how do I use generics to change the following three methods into one generic method ? 我有一个持有业务逻辑的slsb,如何使用泛型将以下三种方法更改为一种泛型方法? The first two are the same db, the third is a different database. 前两个是相同的数据库,第三个是不同的数据库。 Also do the methods require further annotation in relation to transaction ? 这些方法是否还需要与交易有关的进一步注释?

@PersistenceContext(unitName = "db")
private EntityManager myEntityManager;

@PersistenceContext(unitName = "db2")
private EntityManager myDB2EntityManager;

@TransactionAttribute(TransactionAttribute.Required)
public void crud(MyEntity myEntity) throws MyException {
 myEntityManager.merge(myEntity);
}

public void crud(ADifferentEntity aDifferentEntity) throws MyException {
 myEntityManager.merge(aDifferentEntity);
}

public void crud(DB2Entity db2Entity) throws MyException {
 myDB2EntityManager.merge(db2Entity);
}

Many thanks in advance. 提前谢谢了。 Cheers! 干杯!

Not sure if I fully understand the question, but: Since you have two different entity managers there and two different DBs (assuming you're not saving the same data in duplicate to both DBs at the same time, which it appears that you are not), I think it's reasonable to have two different methods in your interface. 不知道我是否完全理解这个问题,但是:由于您那里有两个不同的实体管理器和两个不同的数据库(假设您没有将相同的数据同时复制到两个数据库中,这看起来好像您不是),我认为在界面中使用两种不同的方法是合理的。 (I would name them differently to avoid confusion I think.) (为避免混淆,我会用不同的名称命名。)

To merge the first two how about using a common interface or inherited abstract base class and changing the parameter type to that common type? 要合并前两个,如何使用公共接口或继承的抽象基类并将参数类型更改为该公共类型?

If you require merging of 2 entities from 2 different databases within the same method, you should have JTA configured - as the transaction will span the 2 databases. 如果您需要在同一方法中合并来自2个不同数据库的2个实体,则应该配置JTA-因为事务将跨越2个数据库。

Not too sure what you're trying to do with the generic thing... Are you trying to provide a method to crud eg a T extends AbstractEntity , and then in the crud method, 不太确定您要对通用对象做什么...您是否正在尝试提供一种Crud方法,例如T extends AbstractEntity ,然后在crud方法中,

crud(T entity) {
    if (entity instanceof DB1Entity) then em1.merge(entity) 
      else em2.merge(entity)
}

??? ???

or are you trying to do horizontal partitioning ?: 还是您要进行水平分区?

Multi-user Datasources - Spring + Hibernate , 多用户数据源-Spring + Hibernate

http://www.jroller.com/kenwdelong/entry/horizontal_database_partitioning_with_spring http://www.jroller.com/kenwdelong/entry/horizo​​ntal_database_partitioning_with_spring

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM