Reputation: 1676
I've been looking around for a solution but can't seem to find a good one. I have a complex scenario in which I would like to evaluate the behavior of hibernate optimistic locking vs pessimistic locking
The perfect place to do this would be in a good set of integration tests, but I can't seem to be able find a clean way of starting parallel transactions.
Note that I haven't found a way to create 2 parallel transactions without spawning at least 2 threads (maybe there is a way, I hope you can show me an example of that).
Upvotes: 6
Views: 1120
Reputation: 29997
Adding this as an answer as there's not enough space on the comments:
In the past, I've tested on vanilla Spring by creating different EntityManager/Session and later injecting those. I'm not sure how you can do this from an Spring integration test, but it might spark an idea.
In the following code, Account is a tiny object which is versioned. You can achieve the same, if the Spring Integration flow (or whatever is called) can be instantiated with a custom entity manager.
public void shouldThrowOptimisticLockException() {
EntityManager em1 = emf().createEntityManager();
EntityManager em2 = emf().createEntityManager();
EntityTransaction tx1 = em1.getTransaction();
tx1.begin();
Account account = new Account();
account.setName("Jack");
account.updateAudit("Tim");
em1.persist(account);
tx1.commit();
tx1.begin();
Account account1 = em1.find(Account.class, 1L);
account1.setName("Peter");
EntityTransaction tx2 = em2.getTransaction();
tx2.begin();
Account account2 = em2.find(Account.class, 1L);
account2.setName("Clark");
tx2.commit();
em2.close();
tx1.commit(); //exception is thrown here
em1.close();
}
Upvotes: 3