Search code examples
javamysqlhibernatehqlnamed-query

Java Hibernate Why executeUpdate on namedQuery executes full table update first?


I have a simple NamedQuery like this

@org.hibernate.annotations.NamedQuery(name="namedQuery",query="update entity set .... where id=:id"

I have a method like this

public void updateField(final Entity entity){
    final Session session = currentSession();
    final org.hibernate.Query query= session.getNamedQuery("namedQuery")
            ...loadParameters();
    query.executeUpdate();
    return;     
}

This always works alright but sometimes in this line of code

query.executeUpdate();

Sometimes I see in the console a select from the entity like a full update of the entity. I don't understand why this happens; if I really want to update a simple field why Hibernate updates me all the fields? When this happens the only single update of the namedQuery seems useless because was I think was updated before.

Something like this i see this in the console

Hibernate: 
/* update
    com.models.Entity */ update
        entity 
    set
        BUNCH OF FIELDS
    where
        ID=?

and later I see what I really want the only field being updated

update
    Entity
set
    SINGLE_FIELD_UPDATE  
where
    ID=?

As I mentioned, the full update sometimes appears sometimes do not and sometimes the full update appears twice before the update of the namedQuery being executed!

Why is this? Why does Hibernate fire a full update and something twice the full update before the real field in the namedQuery being executed?

I am missing something?


Solution

  • Please annotate your class with

    @org.hibernate.annotations.Entity( dynamicUpdate = true )
    

    see here