Makoto
Makoto

Reputation: 775

hibernate persistence of an element in a collection

I have a question about the persistence of an object in hibernate.

The context is that I have a user who has multiple roles:

@Entity
@Table(name="users")
public class User implements Serializable {

   @Id
   @GeneratedValue(strategy=GenerationType.IDENTITY)
   @Column(name="user_id")
   private Long idUser;

   @OneToMany
   @JoinColumn(name="user_id")
   private Collection<Role> roles;

}

I want to add another role to the user in a DaoImpl

 public class ShopDaoImpl implements ShopDAO{

   @PersistenceContext
   private EntityManager em;

   @Override
   public void attribuerRole(Role r, Long userID) {
      User u = em.find(User.class, userID);
      u.getRoles().add(r);
      em.persist(r);

   }
 }

I would like to undersand why I need to save only the role r (with persist) and I do not need to update the user for example (em.merge(u) ); although I have modified the user (added a role in its Collection roles;)

Upvotes: 0

Views: 60

Answers (2)

Laurence Geng
Laurence Geng

Reputation: 434

Check your Role class mapping, see if there is some setings over the user field which looks like: ManyToOne(cascade=CascadeType.XXX), if yes, it means when you persist role, the user will persist automatically by hibernate.

Upvotes: 1

JB Nizet
JB Nizet

Reputation: 691755

Because changes you make to a managed object are automatically made persistent by Hibernate. Hibernate keeps a reference to its managed objects in its session and, before committing the transaction, it checks if the entities in the session have been modified. If they have been, then it executes the appropriate SQL queries to write the changes to the database.

This can also happen before the transaction is committed: when you call flush() or when a query is executed (to make sure that the database is modified before the query is executed).

What is a managed entity?

  • any entity that you get from Hibernate: by executing a query returning entities, by calling find() or getReference() or merge(), or by navigating through associations from other managed entities (user.getRoles() for example will return managed entities if user is also managed)
  • any entity that you have passed to persist().

See http://docs.jboss.org/hibernate/core/4.3/manual/en-US/html_single/#objectstate-overview

Upvotes: 1

Related Questions