I have a stateless session bean called SessionCMTBean which uses Container Managed Transaction.
There is only one business method which is exposed to the client through Remote interface called SessionCMT.
This business method calls 2 methods of DAO to update 2 tables.I intentionally make the preparedStatement used in one DAO method to null so that one method succeeds and the other doesn't.But since these 2 methods are inside a single transaction ,so both of them shouldn't succeed.Hence updates to either of the tables shouldn't occur.
Now the problem is that one method successfully updated database while other did not.There should infact be no updates occurring on either of these tables.
Here is the code:
public class SessionCMTBean implements SessionBean
{
.......
.....
public void addAllData(
String empID,String empName,String stockID,String stockName)
{
stockDAO.addStock(stockID,stockName);
stockDAO.addEmp(empID,empName,stockID);
}
}
public class StockDAO
{
......
......
public void addStock(String stockID,String name)
{
Connection connection = datasource.getConnection();
String query = "Insert into jtaStock(stockid,description) values(?,?)";
PreparedStatement preparedStatement = connection.prepareStatement(query);
preparedStatement.setString(1,stockID);
preparedStatement.setString(2,name);
preparedStatement.execute();
}
public void addEmp(String empID,String name,String stockID)
{
Connection connection = datasource.getConnection();
PreparedStatement preparedStatement = connection.prepareStatement (query);
preparedStatement = null; //Exception is thrown here
preparedStatement.setString(1,empID);
preparedStatement.setString(2,name);
preparedStatement.setString(3,stockID);
preparedStatement.execute();
}
}
ejb-jar.xml
<assembly-descriptor>
<container-transaction>
<method>
<ejb-name>SessionWithCMT</ejb-name>
<method-name>addAllData</method-name>
</method>
<trans-attribute>Required</trans-attribute>
</container-transaction>
</assembly-descriptor>
When the client calls business method addAllData(...) on the remote interface,
addStock(..) method successfully inserts data in jtaStock table although addEmp(..) fails.
Is there a problem with the code ???
regards,
kumari