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(); } } }
相關文章
相關標籤/搜索