0

I have the following entities:

@Entity
public class B{

   @OneToMany
   private List<C> cList;

   private Long d;

}

In my managed bean, I need to load a specific b (which is perfectly working) in order to edit the contained attributes (cList, d):

@ManagedBean
public class Bean{

   private B b;

   public void onEvent(Long bId){
      b = bManager.load(bId);
   }
}

The attributes of B will have to be edited using a JSF-Form. I do not want these changes to be reflected to the database.

The problem is pretty much the same like in this (old) thread. But none of the suggestions worked in my case (tried em.flush(), em.detach(), session.evict()).

Is there no solution except deep copying?

Community
  • 1
  • 1
jp-jee
  • 1,502
  • 3
  • 16
  • 21

1 Answers1

0

It is possible to do it, but first would be better to know what hibernate is doing and why you are getting exception. Here is documentation about object states

If you want to access list with objects C or you want to modify some of them, you must fetch it before it gets to your managed bean. By default hibernate is fetching objects lazy and associated objects will be loaded when you access them, but preconditions is to have a transaction and session attached to objects. So in your managed bean objects are detached and list of C cannot be fetch at that time. To solve that problem you must fetch all object that you want to change before they gets to the managed bean. i.e.

   @OneToMany
   @Fetch(FetchMode.JOIN)              // load it with sql join
   private List<C> cList;   

There many other ways you can achieve same result. So now you can update your B and list of C entities and then call update function for your B entity.

Hope it helps.

Petar Butkovic
  • 1,820
  • 15
  • 14
  • fetching is not the problem - i am fetching all the c's (calling cList.size() after loading). Otherwise, the error would occur on rendering the components to edit the c's attibutes. Again: I _have_ anything I need in my managed bean, need to modify it but I do not want to save it (which hibernate seems to try) – jp-jee Oct 02 '14 at 10:37
  • Did you check that your object is really detached in managed bean? Here is example how you can check http://stackoverflow.com/questions/19474399/how-to-identify-an-object-is-transient-or-detached-in-hibernate – Petar Butkovic Oct 03 '14 at 08:06