Class JpaServlet

    • Constructor Detail

      • JpaServlet

        public JpaServlet()
    • Method Detail

      • executeWithinTx

        protected <T> T executeWithinTx​(Callable<T> operation)
                                 throws Exception
        Executes operation within the DB transaction obtained from entityManagerProvider. If operation completes normally, commits the transaction. Otherwise the transaction is rolled back.
        Throws:
        Exception
      • executeWithinTx

        public static <T> T executeWithinTx​(jakarta.inject.Provider<EntityManager> entityManagerProvider,
                                            Callable<T> operation)
                                     throws Exception
        Executes operation within the DB transaction obtained from entityManagerProvider. If operation completes normally, commits the transaction. Otherwise the transaction is rolled back.
        Throws:
        Exception
      • removeEntityManagerFromRequestScope

        public void removeEntityManagerFromRequestScope()
        Removes the stored EntityManager from the scope of the current request.

        If a given app performs some time consuming operations (such as network communication long CPU/GPU intensive computations etc), that need to be surrounded by JPA operations that do not need to be a part of the same transaction, like for example:

         List someRecords = someDbDao.getSomeDataFromDB(); // TX-1 or no TX
         SomeClass results = someExternalNetworkConnector.someLongOperation(someRecords);
         someDbDao.storeSomeStatsAboutResults(results); // TX-2

        then it may significantly improve performance to close the EntityManager after the first (batch of) JPA operation(s) so that other requests may use the underlying connection in the mean time.
        In such case, for the second (batch of) JPA operation(s) a new EntityManager must be obtained. To prevent request-scoped entityManagerProvider from reusing the old closed one, it needs to be removed from the scope.

        Note: If a request is handled by multiple threads, care must be taken to prevent some of them from retaining the old stale instance.