Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
454 views
in Technique[技术] by (71.8m points)

java - Hibernate Idempotent Update

I tried searching this over the net but in vain. Is there a way to use hibernate to perform an idempotent update.

One use case is to use HTTP PUT to update a specific field in the database via a REST API. So for example, if I have a database with columns : Id, Name, Phone, UpdateDate and I update the Phone field (of a specific Id) with the same value multiple times only my first action must update the Phone(and also change my UpdateDate). Subsequent updates must have no effect on the record (and UpdateDate).

While this can be implemented in an application by first getting the record and comparing it against my input value before performing an update. I was wondering whether Hibernate has any inbuilt features?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In hibernate if you get an object and try to modify one of it`s property and commit the transaction. Hibernate compares new values to the old values. Issues an UPDATE for all persistent properties of the entity only if the new value of at least one of the property is different than the old value.

Example:

  1. Find EntityA by id. Hibernate issues a SELECT for the entity (and any non-lazy many-to-one entities), and it remembers the original values. EntityA a = hibernateSession.find(EntityA.class, id);
  2. Set some property on entityA. a.setPhone(newPhoneValue);
  3. Commits the transaction, triggering hibernateSession.flush(). Hibernate compares new values to the old values. Issues an UPDATE for all persistent properties of x if the old and the new value of propertyB are different.

Issue an update like : UPDATE entityA set phone=?, name=?, updateDate=? WHERE id=?

If you want you can use dynamic-update and dynamic-insert in the mapping.

dynamic-update (optional - defaults to false): specifies that UPDATE SQL should be generated at runtime and can contain only those columns whose values have changed.

dynamic-insert (optional - defaults to false): specifies that INSERT SQL should be generated at runtime and contain only the columns whose values are not null.

With dynamic-update set to true hibernate will issue a UPDATE without the name column because it has not change.

UPDATE entityA set phone=?, updateDate=? WHERE id=?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...