I am using hibernate 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?
Scheme example:
Code:
---
|
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
-- THROW Illegal attempt to associate a proxy with two open sessions --
commit transaction 2
|
|
---------------
|
V
commit transaction 1
Code example:
Code:
@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].