Note that there are some explanatory texts on larger screens.

plurals
  1. POSpring hibernate insert race condition
    primarykey
    data
    text
    <p>I am currently having a race issue with Spring Hibernate (transaction by annotation on service and daoImpl classes). Here is what I have encountered:</p> <p>Tables:</p> <ul> <li>Device Type: id (serial), name</li> <li>Device: id (serial), device_identifier, device_type_id, ip_address </li> </ul> <p>Note device_identifier and device_type_id are together unique</p> <p>Here is a snippet of what I have in a multi-thread process:</p> <pre><code> if(deviceDao.findByIdentifierAndTypeId(identifier, typeId) == null){ Device newDevice = new Device(); newDevice.setIdentifier(identifier); newDevice.setTypeId(typeId); deviceDao.add(newDevice); } </code></pre> <p>So what happens is that, I have a server that listens to devices via websockets (probably not important detail here) and the server would first try to determine if the device is already in the database and the device record is created if not already found.</p> <p>Now the problem I have is that the server can process multiple messages from a device (a thread is created per message from a device) and therefore the race condition.</p> <p>So imagine this:</p> <p>Device A sends two messages one after the other:</p> <pre><code> Sends hello message Sends "here is my ip" message | | | | | | does not see device in DB | tries to insert does not see device in DB | tries to insert Insert completed | Failed to insert (Unique key constraints not met) </code></pre> <p>Obviously when the device is to be inserted for the second time, the unique constraint will cause the failure. But I was thinking that when the first insert is completed, Spring would be able to just pick it up and know that when the second thread tries to insert again it wouldn't need to. But this didn't happen despite of various Propogation and Isolation modes that I tried. I must be missing something very fundamental and please point me to the right direction on how I can fix this. Thanks in advance for your replies. I will provide more info if needed/requested.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload