rahul rahul - 1 year ago 90
Java Question

How to rollback a series of persist statements in JPA?

I have a situation where i a need to rollback a series of persist method.
I have a method in my controller class, from where I am calling the persist method.

Controller class:

private jpa.session.ClassMasterFacade ejbFacadeCM;
private jpa.session.StudentMasterFacade ejbFacadeSM;
private jpa.session.ParentsMasterFacade ejbFacadePM;
private jpa.session.AddressMasterFacade ejbFacadeAM;

public String confirmData() {
try {
} catch (Exception e) {
//rollback all
JsfUtil.addErrorMessage(e, ResourceBundle.getBundle ("/resources/Bundle").getString("PersistenceErrorOccured"));
return null;

Example Facade class:

public class ClassMasterFacade extends AbstractFacade<ClassMaster> {

@PersistenceContext(unitName = "sdjv_smsPU")
private EntityManager em;

protected EntityManager getEntityManager() {
return em;

public ClassMasterFacade() {


All other facade classes are similar to the above class. The abstract class is:

public abstract class AbstractFacade<T> {
private Class<T> entityClass;

public AbstractFacade(Class<T> entityClass) {
this.entityClass = entityClass;

protected abstract EntityManager getEntityManager();

public void create(T entity) {

public void edit(T entity) {

public void remove(T entity) {

public T find(Object id) {
return getEntityManager().find(entityClass, id);

I want to rollback all the create method if any exception is found.

I searched and found some answers:

I am new to JPA and just started exploring it. Am I missing some concept?

there is till a problem, dont know if it is related. In all the entity class, i have a autogenerated key as updated. the problem is that if the exception occurs in second create statement, the autogenerated key for the first create statement is generated but still not updated in mysql as excepted..But in case of success all statement, the key sequence is broken.

Entity Class:

@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "class_group_id")
private Integer classGroupId;

Answer Source

Use a javax.transaction.UserTransaction, which is available to you in any standard Java EE environment.

Usage is fairly straightforward, inject it and use the following methods:

  • begin() to start a transaction
  • commit() if all operations were successful and you want to commit the results
  • rollback() if an error occurred and you want to roll back to the point in time when begin() was called

See: Oracle documentation on UserTransaction

UserTransaction tran;


public void confirmData (){

    try {

        // Create's succeeded, commit transaction.
    } catch (Exception e) {
        // Error occurred, rollback transaction
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download