Hibernate manage transaction on standalone application

19 Views Asked by At

I have a small project only have :

  1. implement simple rest api with com.sun.net.httpserver.HttpServer
  2. Hibernate + JPA

as you know , hibernate does not support nested transactions, and i won't use frameworks like Spring or jakarta/javaEE .
I want to know :
Is this good idea to pass EntityManager as parameter to CRUD layer classes ?

public class MyCRUD {

    public static void save(FirstEntity fe, EntityManager em) {
        em.persist(fe);
    }

    public static void save(SecondEntity se, EntityManager em) {
        em.persist(se);
    }
}

public class MyService {
    public static void doSomething(....) {
        // Business logic 
        // Insert into db 
        // ...
        EntityManagerFactory emf = Persistence.createEntityManagerFactory(UNIT_NAME);
        try (EntityManager em = emf.createEntityManager()){
            EntityTransaction tx = em.getTransaction();
            tx.begin();
            MyCRUD.save(fe, em);
            MyCRUD.save(se, em);
            tx.commit();
        }
    }
}

is There any way to use EntityManager inside CRUD Layer (without pass as parameter) and handle transactions on Service layer ?

0

There are 0 best solutions below