How to rollback the transaction while spring controller has runtime exception...

i found some snippet from google i.e,

@Transactional(rollBackFor = Exception.class)

I think this only applicable for service class has the exception.

I need to rollback controller class has any exception.

forexample

@controller
public class test1
{
        public void testing()
        {

        try
        {
        test2.sampletrans()
          int k=5/0; //  what i do from here i got exception
        }
        catch(Exception e)
        {

        }

}

@Service
@Transactional(rollBackFor = Exception.class)
public class test2
{

public void sampletrans()
{
    try
    {
    sessionfactor.getCurrentSession.createSQLquery("update test set a=5");

     int k=5/0; // if i has any exception from here. i think it will be automatically rollback.
    }
    catch(Exception e)
    {

    }

}

may be implement an interface in the controller and pass its instance to the Dao Object

create an interface:

public interface IMyInterface {
    public void rollback(Transaction transaction);
}

in the controller:

public class MyController implements IMyInterface {
    ....
    ....

    public void someDatabaseLogic() {
        Dao dao=new Dao(this);
    }

    @Override
    public void rollback(Transaction transaction) {
        transaction.rollback();
    }
}

in the dao:
public class Dao {
    private IMyInterface mControllerCallback;
    ....
    ....
    public Dao(IMyInterface in) {
        mControllerCallback = in;
    }

}

inside the dao

Transaction transaction = null;
try {
    transaction = session.beginTransaction();
    ....
    ...
} catch(Exception e) {
    mControllerCallBack.rollback(transaction);
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.