nikam03
(Nikam03)
January 5, 2021, 5:50pm
1
Hi ,
Im migrating application from play 2.2 to Play 2.8
Exsisting code has --> try {
em.persists(pc);
em.persists(ds);
}catch(PersistenceException e){
if(e.getCause() instanceof ConstraintViolationException) {
JPA.em().getTransaction().rollback();
JPA.em().getTransaction().begin();
}
}
Question: How can this be handled in Play 2.8 , ```
jpaApi.withTransaction
Im making calls repository.savePC(pc);
resositoryDs.saveDS(ds);
In case of exception both transaction should get rolled back.
Thank you for the help
costa
(Costa)
January 5, 2021, 8:36pm
2
/** * Run a block of code with a newly created EntityManager for the named Persistence Unit. * * @param name The persistence unit name * @param readOnly Is the transaction read-only? * @param block Block of code to execute * @param <T> type of result * @return code execution result */ public <T> T withTransaction(String name, boolean readOnly, Function<EntityManager, T> block) { EntityManager entityManager = null; EntityTransaction tx = null; try { entityManager = em(name); if (entityManager == null) { throw new RuntimeException("Could not create JPA entity manager for '" + name + "'"); }
It seems that the withTransaction method takes care of the transaction. You don’t have to rollback or commit.
Also, why do you start another transaction after rolling back - do you execute something else after?
nikam03
(Nikam03)
January 5, 2021, 10:50pm
3
Thank you for the reply.
Yes after rolling back transaction ,I have to execute select
Line1: repository.savePC(pc);
Line 2: resositoryDs.saveDS(ds);
expecting to get both transaction rolled back in case of any exceptions
then execute repositoryDate.getLatestDate();
currently if any exception occurred at resositoryDs.saveDS(ds); --> this gets rollback but
Line 1 inserted record remains in DB.