Hibernation + logic "ON DUPLICATE KEY"

I am looking for a way to write to save or update , according to the unique key of the table, which consists of several columns).

I want to achieve the same functionality as INSERT ... ON DUPLICATE KEY UPDATE , which means to blindly save the record, and insert a DB / Hibernate new or update an existing one if a 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 SQL and let Hibernate do the work. (I guess this will do a better job - otherwise why use Hibernate?)

+4
source share
3 answers

This is not like a clean approach to me. It would be better to first see if an entity exists with a given key. If so, update it and save if not create a new one.

EDIT

Or maybe consider whether merge () is what you are looking for:

  • if there is a persistent instance with the same identifier that is currently associated with the session, copy the state of this object to the persistent instance
  • If the session does not have a persistent instance, try downloading it from the database or creating a new persistent instance
  • a persistent instance is returned
  • this instance is not associated with the session; it remains disconnected

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

+2
source

You can use saveOrUpdate () from the Session class.

0
source

Hibernate may throw a ConstraintViolationException when trying to insert a row that violates a constraint (including a unique constraint). If you do not get this exception, you can get another general Hibernate exception - it depends on the version of Hibernate and the ability of Hibernate to match the MySQL exception with the Hibernate exception in the version and type of database you are using (I have not tested it for everything).

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

I would be careful in implementing solutions in which you verify that the string exists in the first place. If several sessions update the table at the same time, you can get a race condition. Two processes read the line almost at the same time to see if it exists; they both discover that they are not, and then they both try to create a new line. Someone will win depending on who wins the race.

The best solution is to try to insert the first one, and if she fails, suppose she was already there. However, as soon as you get an exception, you will have to roll back to limit the use of this approach.

0
source

Source: https://habr.com/ru/post/1343164/


All Articles