-
I have written following code to rollback transaction.
But its not working. It still inserts data in database.
package stateless;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.Stateless;
import java.sql.*;
import javax.annotation.Resource;
import javax.ejb.TransactionManagement;
import javax.transaction.SystemException;
import javax.transaction.UserTransaction;
@Stateless
//@javax.ejb.ApplicationException(rollback = true)
@TransactionManagement(javax.ejb.TransactionManagementType.BEAN)
public class TestEjbBean extends Myexception implements TestEjbRemote, TestEjbLocal{
@Resource private javax.transaction.UserTransaction UserTx;
Connection con;
int val=0;
public String getMessage() {
return "Hello Ejb World";
}
// @TransactionAttribute(javax.ejb.TransactionAttributeType.REQUIRED)
public int InsertData(){
try {
UserTx.begin();
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:odbc:test");
Statement st = con.createStatement();
val=st.executeUpdate("INSERT INTO MulTable VALUES(21,13)");
System.out.println("**********AFTER INSERTING INT VALUES*************");
//st.executeUpdate("INSERT INTO MulTable VALUES(a,b)");
//System.out.println("**********AFTER INSERTING WRONG VALUES*************");
if(1==1){
throw new Myexception("HIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII");
}
UserTx.commit();
} catch (Myexception e) {
try {
UserTx.rollback();
System.out.println(e);
}
catch (SystemException ex) {
Logger.getLogger(TestEjbBean.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println(e);
}catch(Exception r){}
return val;
}
}
-
In order to make container taking over the transaction management, you need to use XA datasource instead of get a physical connection to the db.
so you need to change the code as below:
try {
UserTx.begin();
//lookup a xa datasource.
DataSource ds = ic.lookup("your xa datasource");
//then get a indirect connection from datasource.
con = ds.getConnection();
Statement st = con.createStatement();
val=st.executeUpdate("INSERT INTO MulTable VALUES(21,13)");
System.out.println("**********AFTER INSERTING INT VALUES*************");
//st.executeUpdate("INSERT INTO MulTable VALUES(a,b)");
//System.out.println("**********AFTER INSERTING WRONG VALUES*************");
if(1==1){
throw new Myexception("HIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII");
}
UserTx.commit();
} catch (Myexception e) {
try {
UserTx.rollback();
System.out.println(e);
}
catch (SystemException ex) {
Logger.getLogger(TestEjbBean.class.getName()).log(Level.SEVERE, null, ex);
}