12 Replies Latest reply: Aug 24, 2011 11:30 AM by gimbal2 RSS

    persisting new entity does not update other side of relationship?

      Hi all,

      I am not sure if I missed this when learning/reading on ejb3.. I have two objects, a User and a Friends list. A user can have one to many friends. A friends has the many to one back to users. When I persist a new user..there are no friends yet.. that works fine. When I go to persist a friend, I persist the Friend entity..which saves. I even add the friend.setUser(user). For some reason the persisting of friend works..but the user.getFriends() returns 0 friends. I would have thought persisting a new friend entity with the user set, would also update the user one to many mapping as well? It seems I have to do something like:

      List<Friend> friends = user.getFriends();
      if (null == friends){
      friends = new ArrayList<Friend>();

      When I do this.. it then adds the friend and it seems to update the user relationship so that user.getFriends() returns the newly added friend as well.

      Is there a better way to do this? Should I instead just set the new friend on the user list..and that will persist the friend as well?