JPA - When to use getTransaction() when persisting objects

后端 未结 4 1750
长情又很酷
长情又很酷 2020-12-24 12:07

I\'ve recently started working with JPA on the Google App Engine. In reading some examples, I\'ve noticed a couple of variations in the way objects are persisted. In one cas

4条回答
  •  失恋的感觉
    2020-12-24 12:57

    Google App Engine has its transaction management (https://developers.google.com/appengine/docs/java/datastore/transactions) but the JPA transaction interface isn't aware of some of the GAE underlying functionalities (i.e. entity groups).

    So it’s up to your application to decide which operations to perform in a transaction and which not. You should put in a transaction operations that have to be executed atomically.

    Remember as a best practice to perform cascading actions and relationship operations in a transaction because JPA might trigger many queries and it could lead to an inconsistent data situation.

    Example of using transaction with JPA2:

    import javax.persistence.EntityTransaction;
    
    
    EntityTransaction txn = em.getTransaction();
    txn.begin();
    try {
        //do something with your database
        txn.commit();
    } 
    finally {
       if (txn.isActive())
          txn.rollback(); 
    }
    

提交回复
热议问题