Reputation: 47290
I have an slsb holding my business logic, how do I use generics to change the following three methods into one generic method ? 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!
Upvotes: 0
Views: 1114
Reputation: 3644
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?
Upvotes: 2
Reputation: 4381
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.
Not too sure what you're trying to do with the generic thing... Are you trying to provide a method to crud e.g. a T extends AbstractEntity
, and then in the crud method,
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,
http://www.jroller.com/kenwdelong/entry/horizontal_database_partitioning_with_spring
Upvotes: 0