I am using hibernate 4 and spring-aop to handle transactions so that there is always an open transaction on the server side.
I want to create a nested transaction to work on it in isolation but I get an error: Illegal attempt to associate a proxy with two open sessions. See example below:
Entity e2 created with data from a persisted entity e1 and saved in a nested transaction. E1 has a deep graph not completely initialized.
What would be the correct way of creating e2 without throwing an exception?
Example scheme:
---
|
V
begin transaction 1
|
---> Read persisted entity e1
|
|
V
begin transaction 2
create new transient entity e2
copy properties from e1 to e2
save e2
-- THROWS Illegal attempt to associate a proxy with two open sessions --
commit transaction 2
|
|
---------------
|
V
commit transaction 1
Code example:
@Test
public void testSaveInNestedSession() {
// open first session
Session session1 = sessionFactory.openSession();
Transaction transaction1 = session1.beginTransaction();
// get the existing music collection
MusicCollection mc = DbUtil.getMusicCollection(session1, "X Collection");
// create and save a copy of this collection in a nested transaction (will break)
replicateMusicCollection(mc);
transaction1.commit();
session1.close();
}
/**
* Save a copy of the MusicCollection in a new transaction
* for isolation purposes
* @param mc
*/
private void replicateMusicCollection(MusicCollection mc) {
// open nested session
Session session2 = sessionFactory.openSession();
Transaction transaction2 = session2.beginTransaction();
// create a new transient Music Collection
MusicCollection newMusic = new MusicCollection();
newMusic.setName("Collection Y");
newMusic.setOwner(mc.getOwner());
for(AudioCd cd : mc.getCdSet()) {
AudioCd newCd = new AudioCd();
newCd.setAlbumName(cd.getAlbumName());
newCd.setAuthor(cd.getAuthor());
newMusic.addAudioCd(newCd);
}
try {
session2.save(newMusic);
transaction2.commit();
}
catch(HibernateException e) {
e.printStackTrace();
transaction2.rollback();
throw e;
}
session2.close();
}
Maven project with detailed test case at [https://github.com/cemartins/test-cases].
You have to ensure that there is no shared Hibernate managed objects between the 2 sessions. i.e., ensure that a true deep copy of the MusicCollection is done in the replicateMusicCollection() method.
In the code you have posted, if mc.getOwner() represents a Hibernate managed object that is shared, you need to ensure that it is loaded afresh in the nested session.