Nikolay Petkov
Nikolay Petkov

Reputation: 51

How to enable Hibernate @DynamicUpdate functionality?

I am trying to use somehow hibernates dynamic-update functionality for updating of my entities but it does not work. If any property of my entity is NULL this property is also updated but I don't want that.

@Entity
@Table(name = "DOMAIN")
@DynamicUpdate
@SelectBeforeUpdate
public class Domain implements Serializable {
private static final long serialVersionUID = 1L;
     @Id
     @NotNull(message = "Domain name must be provided")
     @Size(min = 1, max = 255)
     @Column(name = "DOMAIN_NAME")
     private String domainName;
     @Size(max = 255)
     @Column(name = "SALUTATION")
     private String salutation;
     @Size(max = 64)
     @Column(name = "FIRST_NAME")
     private String firstName;
     @Size(max = 64)
     @Column(name = "LAST_NAME")
     private String lastName;

///rest of the properties are omitted

But when I try to update my entity with : entityManager.merge(entity);

every property is updated but not only those which I have set.

So where is the problem?

Upvotes: 0

Views: 984

Answers (1)

JB Nizet
JB Nizet

Reputation: 691645

DynamicUpdate doesn't ignore null properties. It generate update statements dynamically, so that properties that have changed are updated, and the ones that haven't changed are not:

Foo foo = em.find(Foo.class, 1L);
foo.setBar("new value");
// leave foo.baz as it is
em.flush();

In the above code, the update query with DynamicUpdate will look like

update foo set bar = 'new value' where id = 1

instead of

update foo set bar = 'new value', baz = 'current value' where id = 1

Setting a property of an entity to null means that the property of this entity should be set to null (and persisted as null in the database), whether you use DynamicUpdate or not.

Upvotes: 1

Related Questions