简体   繁体   中英

Hibernate session error in Vaadin

I´m developing a Vaadin webapp using JPAContainer with hibernate 4.3. I followed the instructions of this link and implemented EntityManager-per-Request pattern successfully. That means the lazy loading works well with JPAContainer

However, every time I need to use pure JPA, it fails to lazy loads.

Here is an example code:

 try {
    entityManagerProvider.getEntityManager().getTransaction().begin();

    List<SubEntity> subEntitiesList = myEntity.getCollectionOfEntities(); //Fails to load

    for (SubEntity subEntity : subEntitiesList) {
        subEntity.doSomething();
        entityManagerProvider.getEntityManager().merge(subEntity);
    }
    entityManagerProvider.getEntityManager().flush();
    entityManagerProvider.getEntityManager().getTransaction().commit();
} catch (Exception ex) {
    entityManagerProvider.getEntityManager().getTransaction().rollback();
}

//datasource is JPAContainer<MyEntity>  type
datasource.removeItem(index);

I have tried this solutions:

  1. Use hibernate.enable_lazy_load_no_trans It opened an session automatically, but it gave a serious warning:

    "Unable to close temporary session used to load lazy collection associated to no session"

Also, when I remove the Entity from the JPAContainer, I receive an error: org.hibernate.PersistentObjectException: detached entity passed to persist

Can someone give me some hints on how to deal with this problem?

I see two approaches.

Merge the changes of a detached entity to database

Just merge the entity and operate on the managed value.

Entity managed = em.merge(entity);

for (SubEntity sub : managed.getSubEntities()) {
    sub.doSomething();
}

Resolve lazy proxies without touching the DB

Find the entity by ID and copy properties to the detached entity.

Entity managed = em.find(entity.getClass(), entity.getId());
entity.setSubEntities(managed.getSubEntities());

For the second option I wrote a generic utility method to initialize detached entities to some depth that maybe you would find it useful.

// initialize lazy collections and collection elements
JpaUtils.initialize(em, entity, 2);

See JpaUtils for source code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM