Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate + "ON DUPLICATE KEY" logic

I am looking for a way to save or update records, according to the table's unique key which is composed of several columns).

I want to achieve the same functionality used by INSERT ... ON DUPLICATE KEY UPDATE - meaning to blindly save a record, and have the DB/Hibernate insert a new one, or update the existing one if the unique key already exists.

I know I can use @SQLInsert( sql="INSERT INTO .. ON DUPLICATE KEY UPDATE"), but I was hoping not to write my own SQLs and let Hibernate do the job. (I am assuming it will do a better job - otherwise why use Hibernate?)

like image 706
Galz Avatar asked Mar 10 '11 11:03

Galz


2 Answers

Hibernate may throw a ConstraintViolationException when you attempt to insert a row that breaks a constraint (including a unique constraint). If you don't get that exception, you may get some other general Hibernate exception - it depends on the version of Hibernate and the ability of Hibernate to map the MySQL exception to a Hibernate exception in the version and type of database you are using (I haven't tested it on everything).

You will only get the exception after calling flush(), so you should make sure this is also in your try-catch block.

I would be careful of implementing solutions where you check that the row exists first. If multiple sessions are updating the table concurrently you could get a race condition. Two processes read the row at nearly-the-same time to see if it exists; they both detect that it is not there, and then they both try to create a new row. One will fail depending on who wins the race.

A better solution is to attempt the insert first and if it fails, assume it was there already. However, once you have an exception you will have to roll back, so that will limit how you can use this approach.

like image 106
rghome Avatar answered Nov 04 '22 03:11

rghome


This doesn't really sound like a clean approach to me. It would be better to first see if an entity with given key(s) exists. If so, update it and save it, if not create a new one.

EDIT

Or maybe consider if merge() is what you're looking for:

  • if there is a persistent instance with the same identifier currently associated with the session, copy the state of the given object onto the persistent instance
  • if there is no persistent instance currently associated with the session, try to load it from the database, or create a new persistent instance
  • the persistent instance is returned
  • the given instance does not become associated with the session, it remains detached

< http://docs.jboss.org/hibernate/core/3.3/reference/en/html/objectstate.html

like image 43
Stijn Geukens Avatar answered Nov 04 '22 05:11

Stijn Geukens