Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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?

like image 378
Bruno Campos Avatar asked Oct 07 '16 11:10

Bruno Campos


2 Answers

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.

like image 129
Vlad Mihalcea Avatar answered Nov 01 '22 14:11

Vlad Mihalcea


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.

like image 36
FuSsA Avatar answered Nov 01 '22 15:11

FuSsA