From: LostInSpace2011 <nu...@jb...> - 2005-08-01 09:04:27
|
Basically the solution is to manually ensure that the relations are within the entity context / session. This is done my attempting a refresh, which might fail with an exception if the bean has not yet been created. org.hibernate.UnresolvableObjectException: No row with given identifier exists [ com.j2anywhere.users.Role#0] Note that this exception is only throws when an existing Role is associated with the new user. if the role does not exist the framework quite happily persist the user, it's role and the join table via manager.persist(user). Yet if the role already exists a exception is thrown. javax.ejb.EJBException: null; CausedByException is: detached entity passed to persist: com.j2anywhere.users.Role To re-attach the entity to the session we refresh it via manager.refresh(role) and then we are in a position to persist the user. It would be nice if the framework could perform this check for us, but at this stage it does not seem to be capable of checking if the contained objects are new or existing one. Also as you have seen from my previous emails doing : | userB.setRoles(userA.getRoles()); is a No-No. We will need to copy the individual roles. But this could be done via: | userB.getRoles().addAll(userA.getRoles()); Client code: | User userA = new User(); | userA.setName("User"); | userA.setSurname("A"); | Role roleA = new Role(); | roleA.setName("RoleA"); | userA.getRoles().add(roleA); | userA = userManager.createUser(userA); | System.out.println(userA); | | User userB = new User(); | userB.setName("User"); | userB.setSurname("A"); | Role foundRole = userManager.findRole("RoleA"); | System.out.println("Found Role : "+foundRole); | userB.getRoles().add(foundRole); | userManager.createUser(userB); | System.out.println(userB); | Within the session bean user : | public User createUser(User user) | { | Iterator>Role< roles = user.getRoles().iterator(); | while (roles.hasNext()) | { | Role role = roles.next(); | try | { | manager.refresh(role); | } | catch (org.hibernate.UnresolvableObjectException e) | { | System.err.println("Unable to refresh role : "+role); | manager.persist(role); | } | } | manager.persist(user); | return user; | } | Within the entity bean user : | @ManyToMany(cascade = {CascadeType.ALL}, fetch = FetchType.EAGER) | public Collection>Role< getRoles() | { | return roles; | } | public void setRoles(Collection >Role< roles) | { | this.roles = roles; | } | View the original post : http://www.jboss.org/index.html?module=bb&op=viewtopic&p=3887668#3887668 Reply to the post : http://www.jboss.org/index.html?module=bb&op=posting&mode=reply&p=3887668 |