This post is in continuation of JPA How to get the value from database after persist
When I execute the following I am getting following exception, how can I resolve
Injecting EntityManagerFactory instead of EntityManager and javax.transaction.Transactional annotation on method solved my issue as shown below.
//Autowire EntityManagerFactory
@PersistenceUnit(unitName = "readwrite.config")
private EntityManagerFactory entityManagerFactory;
//Use below code on create/update
EntityManager entityManager = entityManagerFactory.createEntityManager();
entityManager.getTransaction().begin();
if (!ObjectUtils.isEmpty(entity) && !entityManager.contains(entity)) {
entityManager.persist(entity);
entityManager.flush();
}
entityManager.getTransaction().commit();
I guess the problem here is that although you have defined the bean for the transaction manager, you haven't annotated the create() method with @Transactional
which enables spring transactions.
Also remove the entityManager.getTransaction().commit();
statement as now all the transaction management will be handled by spring, if you leave the statement as it is then you will get the same error again.
you need to remove entityManager.getTransaction().begin() statement and annotate method using @Transactional which enables spring transactions