Good afternoon There is an Example entity with fields: id, name, type, values ​​..

It is required to find the line using the key name, type and update the values ​​of values. If such a line is not found, then insert a new one. Constrain (name, type) is present. Multithreading

I can arrange the update / addition of a row by separate transactions, with record locking, etc., but can this be implemented in hibernate (for example, merge)?

  • This is implemented in any ORM. - Mikhail Vaysman
  • Merge? What do you have in mind? - Denis
  • All that you have listed - adding, updating, transactions, etc. - Mikhail Vaysman
  • I understand what is realized. I don’t understand, if in two different transactions I find out that there is no entry with the key and add the same key, then at the end of one of the transactions, it will trigger. I want one transaction to perform an insert, another update. Can hibernate help with this implementation or should the developer take care of this? - Denis
  • You can adjust the isolation levels. In general, it is your responsibility to prevent or resolve such situations. - Mikhail Vaysman

1 answer 1

Yes, in JPA and HIBERNATE there is a merge method to which a non-persistent entity is passed. The method refers to the database to search for this object. If there is already an object in the database, the method returns a persistent entity that takes into account the state in the database and a new one (which was passed to the method). If there is no object in the database, the method returns a new persistent entity based on the state that was passed to the method. In this sense, the automation problem is solved. However, the problem of synchronization at the transaction level is not solved. For example, in the first transaction the method will show that there is no object yet, but the transaction will be applied in an hour, and in the meantime the second session will add the object to the database. Perhaps the use of a second-level cache will solve the issue of synchronization of the two sessions.

  • Thank, !! I think the question can be removed, since my system may consist of several java virtual machines .... - Denis