I try to do transactions on my project java, and I realise all transactions don’t rollback the rows in DB.
It’s a local project (the DB was MySQL on phpmyadmin, all tables in innoDB).
I try to do an insert (with a transaction), execute an exeption, and rollback the insert DB.
here an exemple of block transaction I use.
EntityManager em = EMF.getEM();
BasketService basketService = new basketService();
EntityTransaction transaction = em.getTransaction();
try{
transaction.begin();
Basket basket = new Basket();
//set basket params.
basketService.insert(em, basket);
if(basket.getId() != 0) //if inserted.
throw new Exception("fake error");
transaction.commit();
}catch(Exception e){
transaction.rollback();
//print error.
}finally{
if(transaction.isActive()) //security.
transaction.rollback();
em.close();
}
here an exemple of service I use.
public class BasketService {
public Basket insert(EntityManager em, Basket basket){
em.persist(basket);
em.flush();
return basket;
}
}
2
Answers
My assumption is that auto commit is enabled on your mysql database (probably default behaviour)
Let’s try setting the property « hibernate.connection.autocommit » to false in your persistence.xml
Check you server configuration. By setting jta=false in standalone datasource, em.rollback() might only rollback changes within the EntityManager’s persistence context. This means:
Changes flushed to the database using em.flush() might not be rolled back.
The database could end up in an inconsistent state, with some data persisted even though the transaction ultimately failed.