views:

105

answers:

2

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!

A: 

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 ?:

http://stackoverflow.com/questions/3853498/multi-user-datasources-spring-hibernate,

http://www.jroller.com/kenwdelong/entry/horizontal_database_partitioning_with_spring

Dzhu
I thought the stateless annotation removes the need for the transaction attribute annotation on each method in ejb3.0 ?
NimChimpsky
Yes, in EJB3, all EJB methods are by default transactional (REQUIRED). So @TransactionAttribute is not required on any of the EJB methods, unless you require a different tx attribute than the default on the method (e.g. REQIURES_NEW)
Dzhu
+1  A: 

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?

Crusader