I had similar problem some time ago.
I had 2 identical schemas - application had to persist to first or second depending on some logic.
It was pure Hibernate, but talking in terms of JPA I will suggest to have 4 persistence units defined in your persistence.xml:
persistence.xml
<persistence-unit name="PU1">
...
</persistence-unit>
<persistence-unit name="PU2">
...
</persistence-unit>
[...]
and DAO class that has injected EntityManager proxies - each for different PU:
@Repository
public class MyDaoImpl implements MyDao {
@PersistenceContext(unitName = "PU1")
private EntityManager em1;
@PersistenceContext(unitName = "PU2")
private EntityManager em2;
...
public void saveToPU1(MyEntity e) {
em1.persist(e);
}
public void saveToPU2(MyEntity e) {
em2.persist(e);
}
...
}
Of course em1
annotated with @PersistenceContext(unitName="PU1")
is Spring's proxy to Hibernate session and becomes open and bound with current thread only if that thread tries to use it.