Managing Multiple Database Connections [message #1427105] |
Fri, 19 September 2014 18:18 |
Leonardo Jines Messages: 1 Registered: September 2014 |
Junior Member |
|
|
I've been struggling with this problem for days,
Here is the scenario: I have several databases, one for each of my customers, all of them with the same structure(same tables and columns), so my application needs to decide at runtime with which one it needs to connect. I'm using JPA2, EclipseLink and EJB3.
My first attempt was to implement a custom EntityManager with all the logic to performs the operations on the right database, then I configured this EntityManager as an Stateless EBJ in order to make it possible to inject it with the @EBJ annotation. I coundn't make it work because it was throwing an exception when trying to inject the EntityManager.
So I decided to try something else, I've created EntityManagerFactory and I passed the JTA_DATASOURCE to it(after decide at runtime which one to use), so it could connect to the right database.
Here is the code:
@Stateless
@TransactionManagement(TransactionManagementType.CONTAINER)
public class TestEntDAO {
private EntityManager em;
private EntityManagerFactory emf;
@PostConstruct
public void init() {
em = getEntityManager();
}
public EntityManager getEntityManager() {
Map props = new HashMap();
props.put(PersistenceUnitProperties.TRANSACTION_TYPE, "JTA");
props.put(PersistenceUnitProperties.JTA_DATASOURCE, dataSourceName());
emf = Persistence.createEntityManagerFactory("testePU", props);
em = emf.createEntityManager();
return em;
}
public String dataSourceName(){
if(someCondition){
return "db1";
}else{
return "db2";
}
}
}
This worked perfectly, the only problem is that the transaction is not managed by the container, so I had to explicitly mark the transaction's boundaries(call begin() and commit()). I could just use the @PersistenceContext annotation to make it work, but then I wouldn't have the EntityManagerFactory to pass the datasource.
Does anyone know of a way to use the Container-Managed Transactions(CMT) and still be able to pass the datasource?
|
|
|
|
Powered by
FUDForum. Page generated in 0.02856 seconds