Trying to rollback the previous write to database using Spring transaction for POC and learning purposes.
There are two functions that are part of the same transaction namely: insert and then update. The insert successfully writes to database using Hibernate 3.2. I throw a Runtime exception from update on purpose to exercise rollback of insert. Even though update throws the Runtime exception, the data inserted by insert method stays committed in database and does not get rolled back.
org.poc.tx.Manager class has insert and update methods.
Following is the XML:
<aop:config>
<aop

ointcut
id="myOperation"
expression="execution(* org.poc.tx.Manager.*(..))"
/>
<aop:advisor
pointcut-ref="myOperation"
advice-ref="myTxAdvice"
/>
</aop:config>
<tx:advice id="myTxAdvice" >
<tx:attributes>
<tx:method
name="*"
read-only="true"
propagation="REQUIRED"
isolation="READ_COMMITTED"
timeout="5"
/>
</tx:attributes>
</tx:advice>
My assumption is, the above XML should run both Manager.insert() and Manager.update() within a single transaction will rollback insert(), if update() throws RuntimeException.
I have a main method that calls update and insert as follows:
public static void main(
String args[]){
ApplicationContext ctx = new ClassPathXmlApplicationContext("my.xml");
Manager manager = (Manager) ctx.getBean("manager");
manager.insert();
manager.update();
}
The rollback successfully works, if I throw a RunTime exception inside insert method, right after successfully inserting the data as follows:
public void insert(final MyObj myObj){
HibernateCallback callback = new HibernateCallback() {
public Object doInHibernate(Session session)
throws HibernateException,SQLException {
session.insert(myObj);
throw new RuntimeException("ex thrown to rollback");
}
};
hibernateTemplate.execute(callback);
}
But if I want to spread it out to TWO separate methods in Manager class and want both the methods to participate in the same transaction, what should I do?
In a nutshell:
I want both Managaer.insert() and Manager.update() to participate in the same transaction.
I am invoking these two methods as follows in my main method:
manager.insert();
manager.update();
Can I invoke them separately and still make them participate in the same transaction?