kitoha commented on PR #8210:
URL: https://github.com/apache/gravitino/pull/8210#issuecomment-3218094799

   hi, @yuqi1129 .  @justinmclean .
   
   The changes have been completed. The modifications are as follows.
   
   For doWithCommit, doWithCommitAndFetchResult, etc., on success we commit and 
then close the session and clear the ThreadLocal. Conversely, on failure we 
rollback, then close the session and clear the ThreadLocal.
   
   doWithoutCommitAndFetchResult, doWithoutCommit, and getWithoutCommit are 
used in this project both as standalone methods and also under 
doMultipleWithCommit.
   To handle both cases, I added a function to the SqlSessions class to check 
the current session state:
   
   ```
   public static SqlSession peekSqlSession() {
     return sessions.get();
   }
   
   ```
   
   Using this function, we can check at method entry whether a session is 
already open. If it is open, we assume there is a prior point that uses the 
session, and we changed these methods not to close the session.
   
   The method that contains this logic is shown below.
   
   ```
   public static <T, R> R doWithoutCommitAndFetchResult(Class<T> mapperClazz, 
Function<T, R> func) {
     SqlSession existing = SqlSessions.peekSqlSession(); // load current session
     boolean owner = (existing == null);                 // determine if a 
session exists
     try {
       T mapper = SqlSessions.getMapper(mapperClazz);    // create if absent, 
otherwise reuse
       return func.apply(mapper);
     } finally {
       if (owner) {                                      // if created here, 
clean it up
         SqlSessions.rollbackAndCloseSqlSession();
       }
     }
   }
   
   ```
   
   doMultipleWithCommit can run operations that call getWithoutCommit-style 
functions, so I added logic to open a session up front. The change is below.
   
   ```
   public static void doMultipleWithCommit(Runnable... operations) {
     SqlSession existing = SqlSessions.peekSqlSession();
     boolean owner = (existing == null);
     if (owner) {
       SqlSessions.getSqlSession();                      // open a session if 
none is open
     }
   
     try {
       Arrays.stream(operations).forEach(Runnable::run); // share the same 
session across operations
       if (owner) SqlSessions.commitAndCloseSqlSession();
     } catch (Exception e) {
       if (owner) SqlSessions.rollbackAndCloseSqlSession();
       throw e;
     }
   }
   ```
   
   
   Additionally, I added a unit test named SessionUtilsTest.
   I would appreciate your review of these changes when you have time. Thank 
you.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to