Do you need a database transaction for reading data?

前端 未结 2 1213
旧巷少年郎
旧巷少年郎 2020-11-28 20:23

When I try to read data from the database, at least using

((Session)em.getDelegate()).createCriteria()

an exception is throws saying that a tra

2条回答
  •  隐瞒了意图╮
    2020-11-28 20:37

    Accoring to my experience with JPA implementation in J2EE, a Transaction manager is always needed in order to perform CRUD operation safety, by guaranteeing a rollback in order to preserve data integrity.

    Enterprise applications use different resources to save data and send messages like a database or message queue. If we want to query these resources sequentially and to cancel the whole operation once a problem occurs, we have to put this query in a unit of work so that will be executed as a whole.

    You could define it:

    • by using related annotations (as shown in the questions); in this way, the container loads automatically the transaction manager for a given persistence context;

    • by injecting manually the transaction manager, as follows:

      public class sample {
      
          @PersistenceContext
          EntityManager em;
      
          // Injected transaction manager
          @Inject
          UserTransaction utx;
      
          private static final String[] GAME_TITLES = {
              "Super Mario Brothers",
              "Mario Kart",
              "F-Zero"
          };
      
          private void clearData() throws Exception {
              utx.begin();
              em.joinTransaction();
              System.out.println("Dumping old records...");
              em.createQuery("delete from Game").executeUpdate();
              utx.commit();
          }
      
          private void insertData() throws Exception {
              utx.begin();
              em.joinTransaction();
              System.out.println("Inserting records...");
              for (String title : GAME_TITLES) {
                  Game game = new Game(title);
                  em.persist(game);
              }
              utx.commit();
              // clear the persistence context (first-level cache)
              em.clear();
          }
      
          // ...
      
      }
      

    Spring Data, as JPA-spec implementation, may follow the same approach.

    You could find more information by reading the following article: Java_Persistence/Transactions.

提交回复
热议问题