I have two (or more) Java themes that create, update and delete objects from mysql database using JPA. To do this, I have a PersistenceLayer class that creates an EntityManager and provides save, update, and delete methods for all of my objects, which look like this:
public void saveEntity(Entity entity) {
manager.getTransaction().begin();
manager.persist(entity);
manager.getTransaction().commit();
}
public void saveEntity2(Entity2 entity) {
manager.getTransaction().begin();
manager.persist(entity);
manager.getTransaction().commit();
}
If one thread enters the saveEntity operation and the other saveEntity2 at the same time, both will try to get the transaction from the EntityManager, which will fail. However, I always thought that the underlying database could manage several transactions, especially if both work on different rows or even different tables. Of course, I could synchronize the blocks, but this would mean that at the same time only one connection to the database is possible, which will not be scaled for several users creating multiple threads.
What wrong assumption am I making here? Is it possible to send multiple transactions to the database via JPA and allow the DB concurrency descriptor?
source
share