0

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].

4

1 回答 1

0

您必须确保两个会话之间没有共享的 Hibernate 托管对象。即,确保 MusicCollection 的真正深层副本在 replicateMusicCollection() 方法中完成。

在您发布的代码中,如果 mc.getOwner() 表示共享的 Hibernate 托管对象,您需要确保它在嵌套会话中重新加载。

于 2015-06-10T22:12:57.870 回答