Hibernate Facts: Knowing flush operations order matters

Hibernate Tips

Vlad Mihalcea

Hibernate shifts the developer mindset from thinking SQL into thinking object state transitions. According to Hibernate Docs entity may be in one of the following states:

  • new/transient: the entity is not associated to a persistence context, be it a newly created object the database doesn’t know anything about.
  • persistent: the entity is associated to a persistence context (residing in the 1st Level Cache) and there is a database row representing this entity.
  • detached: the entity was previously associated to a persistence context, but the persistence context was closed, or the entity was manually evicted.
  • removed: the entity was marked as removed and the persistence context will remove it from the database at flush time.

Moving an object from one state to another is done by calling the EntityManager methods such as:

  • persist()
  • merge()
  • remove()

Cascading allows propagating a given event from a parent to a child, also easing managing entities…

View original post 173 more words

Advertisements

Hibernate Facts: Favoring bidirectional Set(s) vs List(s)

Vlad Mihalcea

Hibernate is a great ORM tool, and it eases development considerably, but it has a lot of gotchas you must be aware of if you want to use it properly.

On medium to large projects it’s very common to have bidirectional parent-child associations, which allow us to navigate both ends of a given relationship.

When it comes to controlling the persist/merge part of the association, there are two options available. One would be to have the @OneToMany end in charge of synchronizing the collection changes, but this is an inefficient approach, which is very well described here.

The most common approach is when the @ManyToOne side controls the association and the @OneToMany end is using the “mappedBy” option.

I will discuss the latter approach, since it’s the most common and the most efficient one, in terms of the executed queries number.

So, for bidirectional collections we could use a…

View original post 605 more words