0

The following code does not help in roll back even if I throw null pointer exception at update() method. Everytime it inserts values into the database if I run the code. Please help me how can I roll back the transaction if null pointer is thrown at update() method. Am I missing something in the code?

@TransactionManagement(value = TransactionManagementType.CONTAINER)
public class Bean implements RemoteIF {

    @TransactionAttribute(TransactionAttributeType.REQUIRED)
    public void insertIntoDb() {

        insert();
        update();


    }


    private Integer update() {
val=0;      
try {
            Connection con = DbConn.getConnection();
            Statement st = con.createStatement();
            val1 = st.executeUpdate("INSERT INTO tab VALUES('ab')");
            st.close();
            throw new NullPointerException();

        } catch (Exception e) {
            System.out.println(e);
        }

        return val;
    }

    private Integer insert() {
        int val = 0;

        try {

            Connection con = DbConn.getConnection();
            Statement st = con.createStatement();
            val = st.executeUpdate("INSERT INTO tab VALUES('bnm')");
            st.close();

        } catch (Exception e) {
            System.out.println(e);
        }

        return val;
    }
}
Niklas
  • 13,005
  • 23
  • 79
  • 119
  • Why aren't you using JPA? Also refer online tutorial http://docs.oracle.com/javaee/6/tutorial/doc/ to know more about transaction propagation, rollback etc. in EJB – Nayan Wadekar Jan 16 '12 at 15:24

1 Answers1

0

Couple things that stick out at me as suspect.

  • No @Stateless, @Stateful or @Singleton annotation on the Bean class. Unless you've declared the bean in an ejb-jar.xml file, then this is not getting recognized as an EJB. Definitely double check that.

  • The DbConn.getConnection() looks suspiciously like you might be trying to manage database connections yourself. If you have any code that uses the DriverManager or does new FooDataSource(), then that is definitely the problem. If you want transaction management to work you have to get all resources from the container via either

    • Injection via a @Resource DataSource datasource field in the EJB class
    • JNDI lookup of java:comp/env/yourDataSource, where yourDataSource is the name of a datasource you configured in the ejb-jar.xml or declared on the bean class via using @Resource(type=DataSource.class, name="youDataSource") -- that annotation goes on the class itself rather than a method or field.

See also these answers for some insight as to how transaction management works:

Community
  • 1
  • 1
David Blevins
  • 19,178
  • 3
  • 53
  • 68