Skip to content

Commit caac996

Browse files
committed
feat: add enhanced transaction management helpers
- Add executeInTransaction() method for operations returning values - Add executeInTransactionVoid() method for void operations - Both methods include proper rollback handling on exceptions - Improves transaction safety and error handling - Adds required Function and Consumer imports These helpers can be used by subclasses for safer transaction management.
1 parent 53c525d commit caac996

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

src/main/java/jazzyframework/data/BaseRepositoryImpl.java

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@
1212
import java.util.ArrayList;
1313
import java.util.List;
1414
import java.util.Optional;
15+
import java.util.function.Consumer;
16+
import java.util.function.Function;
1517
import java.util.logging.Logger;
1618

1719
/**
@@ -386,4 +388,47 @@ public void deleteInBatch(Iterable<T> entities) {
386388
public void deleteAllInBatch() {
387389
deleteAll();
388390
}
391+
392+
/**
393+
* Helper method to execute operations in a transaction with proper rollback handling.
394+
*
395+
* @param operation the operation to execute
396+
* @param <R> the return type
397+
* @return the result of the operation
398+
*/
399+
protected <R> R executeInTransaction(Function<Session, R> operation) {
400+
try (Session session = sessionFactory.openSession()) {
401+
Transaction transaction = session.beginTransaction();
402+
try {
403+
R result = operation.apply(session);
404+
transaction.commit();
405+
return result;
406+
} catch (Exception e) {
407+
if (transaction.isActive()) {
408+
transaction.rollback();
409+
}
410+
throw e;
411+
}
412+
}
413+
}
414+
415+
/**
416+
* Helper method to execute void operations in a transaction with proper rollback handling.
417+
*
418+
* @param operation the operation to execute
419+
*/
420+
protected void executeInTransactionVoid(Consumer<Session> operation) {
421+
try (Session session = sessionFactory.openSession()) {
422+
Transaction transaction = session.beginTransaction();
423+
try {
424+
operation.accept(session);
425+
transaction.commit();
426+
} catch (Exception e) {
427+
if (transaction.isActive()) {
428+
transaction.rollback();
429+
}
430+
throw e;
431+
}
432+
}
433+
}
389434
}

0 commit comments

Comments
 (0)