Bruno Campos Bruno Campos - 1 year ago 89
Java Question

How to update only a part of all entity attributes with Hibernate

I receive a JSON with 30 fields, and my entity is built from this JSON.
The problem is: two fields shouldn't be updated (two dates).

If I use

, both fields will be updated.

How can I avoid that those 2 fields get updated?

Maybe using criterion.Example?

Is there some way to do this without me writing a ton of HQL?

Answer Source

This article explains in great details your question, but I'm going to summarize it here as well.

If you never want to update those two fields, you can mark them with updatable=false:

@Column(name="CREATED_ON", updatable=false)
private Date createdOn;

Once you load an entity and you modify it, as long as the current Session or EntityManager is open, Hibernate can track changes through the dirty checking mechanism. Then, during flush, an SQL update will be executed.

If you don't like that all columns are included in the UPDATE statement, you can use dynamic update:

public class Product {
   //code omitted for brevity

Then, only the modified columns will be included in the UPDATE statement.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download