I'm having a rather unusual problem, but I'm looking for a solution.
I have a scenario where I have several database bases (postgresql) allocated on multiple clients, all databases have the same structure, but with different records.
I have a java application with jpa
, ecliselink
and ejb 3
, already ready and working, today I use EntityManager to let the container manage the transactions for me (CMT) I do not need to be giving begin and commit, it resolves when I execute in the best way.
Well, with this in mind, I need to continue to use this framework and can not switch to BAN (Bean Managed Transaction), I need to continue using CMT (for larger reasons). Searching and studying a lot of the concept I was able to perform the functionality of connecting to several bases with JTA, but that way I could not get it to be managed by the container (CMT), I would have to give the begin and commit. I'm going to post the code that I was able to perform this function, if anyone knows how to leave the transaction as CMT following this basis of reasoning I would appreciate it.
The code below works but is not running as CMT, it only persists if you have begin and commit:
@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()); // <- Aqui será injetado o cliente que está logado, pegando a base dele.
emf = Persistence.createEntityManagerFactory("testePU", props);
em = emf.createEntityManager();
return em;
}
public String dataSourceName(){
if(someCondition){
return "db1";
}else{
return "db2";
}
}
public salvar(Tabela tab){
em.persist(tab);
} //<-- quando termia esse método era para dar o commit automatico (CMT), mais não esta sincronizando as transações.
}
Anyone who understands JPA well could help me?
Comment : If someone says to use multiple @PersistenceContext(unitName = "db1")
, I can not use it that way, because if any IP goes out or gives a problem on some basis the application does not go up, giving a pain head, I've also tried to use Multitenancy did not fit in that case.