Since I migrated to Hibernate 6.x+ I started having problems with shared sessions in unit sessions
I have a problem where I have the following structure:
I have a test that first creates a record (banana).
After that, I have a concurrency test that triggers 10 threads in 15 iterations that try to delete the record (banana), but I am receiving the message:
Caused by: org.hibernate.NonUniqueObjectException: A different object with the same identifier value was already associated with the session : [banana#123]
This behavior did not occur in version 5.x of hibernate, it only started in version 6.x
Below is an example of how I set up my test
@SpringBootTest
@RunWith(SpringRunner.class)
public class BananaConcurrentDeletedTest {
private static final int THREADS = 10;
private static final int ITERATIONS = 15;
private static final String BANANA_ID = "123";
@Autowired
private BananaConcurrentDeletedFixture fixture;
@Test
public void ensureConcurrentBananaIsCorrect() throws Exception {
createBanana();
Set<String> bananaIds = new HashSet<>();
ids.add(BANANA_ID);
Target target = new Target(ids);
for (int i=0; i<THREADS; i++) {
Thread thread = new Thread(target);
thread.start();
}
target.endLatch.await();
}
private void createBanana() throws Exception {
this.fixture.createBanana(BANANA_ID);
}
private void deleteBanana() throws Exception {
this.fixture.createBanana(BANANA_ID);
}
}
My Target implemtation:
private class Target implements Runnable {
private final CountDownLatch startLatch = new CountDownLatch(THREADS);
private final CountDownLatch endLatch = new CountDownLatch(THREADS);
private final Set<String> ids;
public Target(Set<String> ids) {
this.ids = ids;
}
@Override
public void run() {
try {
startLatch.countDown();
startLatch.await();
for (int i=0; i<ITERATIONS; i++) {
deleteBanana(this.ids);
}
} catch (Exception ex) {
throw new RuntimeException(ex);
} finally {
endLatch.countDown();
}
}
}