Advertisement
Guest User

Untitled

a guest
Jan 18th, 2017
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.20 KB | None | 0 0
  1. public class EntityManagerHelper {
  2. public static <ENTITY_TYPE> void persistInTransaction(EntityManager entityManager, ENTITY_TYPE entity) {
  3. executeInTransaction(entityManager, () -> entityManager.persist(entity));
  4. }
  5.  
  6. public static <EC> void removeAll(EntityManager em, Class<EC> entityClass) {
  7. executeInTransaction(em, () -> {
  8. List<EC> all = findAll(em, entityClass);
  9. for (EC entity : all) {
  10. em.remove(entity);
  11. }
  12. });
  13. }
  14.  
  15. public static <EC> List<EC> findAll(EntityManager em, Class<EC> entityClass) {
  16. CriteriaBuilder cb = em.getCriteriaBuilder();
  17. CriteriaQuery<EC> criteria = cb.createQuery(entityClass);
  18. criteria.from(entityClass);
  19. return em.createQuery(criteria).getResultList();
  20. }
  21.  
  22. private static void executeInTransaction(EntityManager entityManager, TransactionExecutor transactionExecutor) {
  23. try {
  24. entityManager.getTransaction().begin();
  25. transactionExecutor.executeInTransaction();
  26. entityManager.getTransaction().commit();
  27. } catch (RuntimeException e) {
  28. if (entityManager.getTransaction().isActive()) {
  29. entityManager.getTransaction().rollback();
  30. }
  31. throw e;
  32. }
  33. }
  34.  
  35. @FunctionalInterface
  36. public interface TransactionExecutor {
  37. void executeInTransaction();
  38. }
  39. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement