仔细看看j2ee tutorial吧:
There are two ways to roll back a container-managed transaction. First, if a system exception is thrown, the container will automatically roll back the transaction. Second, by invoking the setRollbackOnly method of the EJBContext interface, the bean method instructs the container to roll back the transaction.
因此有三种方法:
1。sessionBean不要Catch findXXX()调用扔出来的系统Exception,
public void createSection(String id, String name, String parentId, String type, String depth) {
Section section = sectionHome.create(id,name,depth,type); section.setParent(sectionHome.findByPrimaryKey(parentId)); }
|
2。你Catch findXXX() Exception后再扔EJBException
public void createSection(String id, String name, String parentId, String type, String depth) { try{ Section section = sectionHome.create(id,name,depth,type); section.setParent(sectionHome.findByPrimaryKey(parentId)); System.out.println("对象已经创建"); }catch(Exception e){ System.out.println(e.getMessage()); throw e; } }
|
3。调用EJBContext.setRollbackOnly()
public void createSection(String id, String name, String parentId, String type, String depth) { try{ Section section = sectionHome.create(id,name,depth,type); section.setParent(sectionHome.findByPrimaryKey(parentId)); System.out.println("对象已经创建"); }catch(Exception e){ System.out.println(e.getMessage()); ctx.setRollbackOnly(true);} }
|
第一种办法最简单明了;如果要跟踪错误用第二种;第三种不推荐。