EJB之JPA(事务回滚)
package cn.com.leadfar.jpa;import java.util.Random;import javax.naming.InitialContext;import javax.transaction.UserTransaction;import cn.com.leadfar.jpa.StudentManager;import junit.framework.TestCase;public class StudentManagerClient extends TestCase{ public void testAddStudent01() throws Exception{ InitialContext context = new InitialContext(); StudentManager sm = (StudentManager)context.lookup("StudentManager/remote"); for(int i=0; i<10; i++){ sm.addStudent("学生"+new Random().nextInt(99999)); if(i > 5){ throw new RuntimeException("异常!"); //数据库依然会插进去数据. } } } public void testAddStudent02() throws Exception{ InitialContext context = new InitialContext(); StudentManager sm = (StudentManager)context.lookup("StudentManager/remote"); //JTA的事务管理由UserTransaction管理. UserTransaction utx = (UserTransaction)context.lookup("UserTransaction"); try{ utx.begin(); //没有数据会插入数据库.整个事务都回滚. for(int i=0; i<10; i++){ sm.addStudent("学生"+new Random().nextInt(99999)); if(i > 5){ throw new RuntimeException("异常!"); } } utx.commit(); }catch(Exception e){ utx.rollback(); e.printStackTrace(); } } }
TAG: