MySQL supports an "Place ... ON DUPLICATE KEY UPDATE ..." syntax that enables you to definitely "blindly" place in to the database, and fall to upgrading the present record if a person is available.

This really is useful when you wish quick transaction isolation and also the values you need to update to rely on values already within the database.

Like a contrived example, let us say you need to count the amount of occasions a tale is seen on the blog. One method to do this with this particular syntax may be:

 Place INTO story_count (id, view_count) VALUES (12345, 1)

 ON DUPLICATE KEY UPDATE set view_count = view_count + 1

This is more effective and much more effective than beginning a transaction, and handling the inevitable exceptions that occur when new tales hit the leading page.

Exactly how should we perform the same, or accomplish exactly the same goal, with Hibernate?

First, Hibernate's HQL parser will throw the best because it doesn't comprehend the database-specific key phrases. Actually, HQL does not like every explicit card inserts unless of course this is an "Place ... Choose ....".

Second, Hibernate limits SQL to chooses only. Hibernate will throw the best should you make an effort to call session.createSQLQuery("sql").executeUpdate().

Third, Hibernate's saveOrUpdate doesn't suit you perfectly within this situation. Your results will pass, however you will get production failures for those who have several customer per second.

Will I need to subvert Hibernate?

Perhaps you have checked out the Hibernate @SQLInsert Annotation?



@SQLInsert( sql="Place INTO story_count(id, view_count) VALUES (?, ?)

 ON DUPLICATE KEY UPDATE set view_count = view_count + 1")

public class StoryCount