下面的代码对回滚没有帮助,即使我在update()方法中抛出空指针异常。如果我运行代码,每次它都会将值插入数据库中。请告诉我,如果update()方法抛出空指针,如何回滚事务。我是不是在代码中遗漏了什么?
@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;
}
}发布于 2012-01-18 08:19:28
有几件事让我觉得很可疑。
Bean类上没有@Stateless、@Stateful或@Singleton注释。除非您在ejb-jar.xml文件中声明了bean,否则不会将其识别为EJB。一定要仔细检查。DbConn.getConnection()看起来很可疑,您可能正在尝试自己管理数据库连接。如果您有任何使用DriverManager或执行new FooDataSource()的代码,那么这肯定是问题所在。如果您希望事务管理正常工作,则必须通过从容器中获取所有资源
- 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.
另请参阅这些答案,以了解事务管理是如何工作的:
https://stackoverflow.com/questions/8875249
复制相似问题