Ricardo Gladwell
Ricardo Gladwell

Reputation: 3787

Can I configure Hibernate/JPA to update an entity record when only non-timestamp fields have been modified?

At the moment I have an Hibernate entity class as follows:

@Entity
@Table(name = "entity")
public class Entity implements Serializable {

    private static final long serialVersionUID = 2040757598327793105L;

    @Id
    @Column
    private int id;

    @Column
    private String data;    

    @Column(name = "last_modified")
    @Temporal(TemporalType.TIMESTAMP)
    private Date lastModified;
}

I've found that even when the non-timestamp fields are not modified (i.e. the data field) a call to merge still updates the timestamp. I would like the timestamp to only update when other data fields have changed.

Is there anyway I can prevent calls to merge making a SQL UPDATE when all other data fields are not modified, or do I have to explicitly check for this myself in the code?

Upvotes: 2

Views: 4874

Answers (1)

Bozho
Bozho

Reputation: 597076

Update (thanks to comment):

Since v4 of Hibernate @Entity annotation is deprecated and for allowing dynamic updates you should use @DynamicUpdate(true) (in conjunction with @SelectBeforeUpdate(true))


If you want to prevent unmodified fields to be included in UPDATE queries, add this on your entity:

@org.hibernate.annotations.Entity(dynamicUpdate=true) // update only changed fields
public class ...

Upvotes: 3

Related Questions