天天看點

JPA - EntityTransaction與事務

EntityTransaction 接口用來管理資源層實體管理器的事務操作,通過調用實體管理器的getTransaction方法 獲得其執行個體。

其常用方法如下:

① begin

用于啟動一個事務,此後的多個資料庫操作将作為整體被送出或撤消。

若這時事務已啟動則會抛出 IllegalStateException 異常。

② commit

用于送出目前事務。

即将事務啟動以後的所有資料庫更新操作持久化至資料庫中。

③ rollback

撤消(復原)目前事務。

即撤消事務啟動後的所有資料庫更新操作,進而不對資料庫産生影響。

④ setRollbackOnly

使目前事務隻能被撤消。

⑤ getRollbackOnly

檢視目前事務是否設定了隻能撤消标志。

⑥ isActive

檢視目前事務是否是活動的。

如果傳回true則不能調用begin方法,否則将抛出 IllegalStateException 異常。

@Before
    public void init(){
        entityManagerFactory = Persistence.createEntityManagerFactory("jpa-1");
        entityManager = entityManagerFactory.createEntityManager();
        //必須先擷取事務執行個體
        transaction = entityManager.getTransaction();
        //開啟事務
        transaction.begin();
    }

    @After
    public void destroy(){
        //送出事務
        transaction.commit();
        entityManager.close();
        entityManagerFactory.close();
    }