How to update only a part of all entity attributes with Hibernate
Solution 1
If you never want to update those two fields, you can mark them with @Column(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 a dynamic update:
@Entity
@DynamicUpdate
public class Product {
//code omitted for brevity
}
Then, only the modified columns will be included in the UPDATE
statement.
Solution 2
Do like this example :
public class UpdateMethodDemo {
public static void main(String[] args) {
Session session = HibernateUtil.getSessionFactory().openSession();
Student s = studentService.getById(1);
s.setNom("FuSsA");
session.beginTransaction();
session.update(s);
session.getTransaction().commit();
session.close();
}
}
Edit:
you can use @Transient
annotation to indicate that a field is not to be persisted in the database.
Bruno Campos
Updated on June 06, 2022Comments
-
Bruno Campos almost 2 years
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
entity.merge
, 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?
-
Bruno Campos over 7 yearsThank you. I know this is an option, but maybe there is something simpler.
-
Robert Niestroj over 7 yearsCould you also elaboate on
@SelectBeforeUpdate
(docs.jboss.org/hibernate/orm/5.2/javadocs/org/hibernate/…) ? Because@DynamicUpdate
indeeed updates only the changed coulns but when my entity contains 5 foreign keys before and updates it selects all this relationships even though they are not changed. I would like to get rid of this unnecessary selectes before and update. For me @SelectBeforeUpdate(false) does not work the way i think it should work.