0

I am new to Hibernate and I was wondering if I should instantiate EntityManager for every method of my repositories or I can just use one EntityManager object for all the methods in my repository.

Here's my code:

public class ActivityRepositoryImpl extends BaseRepositoryImpl < Activity, Long > implements ActivityRepository {

    public ActivityRepositoryImpl(EntityManagerFactory entityManagerFactory) {
        super(entityManagerFactory);
    }

    @Override
    public void save(Activity activity) {
        EntityManager entityManager = entityManagerFactory.createEntityManager();
        entityManager.getTransaction().begin();
        entityManager.persist(activity);
        entityManager.getTransaction().commit();
        entityManager.close();
    }

    @Override
    public void update(Activity activity) {
        EntityManager entityManager = entityManagerFactory.createEntityManager();
        entityManager.getTransaction().begin();
        entityManager.merge(activity);
        entityManager.getTransaction().commit();
        entityManager.close();
    }
}
Mark Rotteveel
  • 90,369
  • 161
  • 124
  • 175
  • opinions seem to deviate here. going by this article, you're doing it the right way (https://www.baeldung.com/hibernate-entitymanager), others seem to use the same manager for everything. However, the important sentence I found here is that `the EntityManager instances are not thread-safe`. – thinkgruen Aug 08 '21 at 16:17
  • If you are using Spring, I'd let it handle the `EntityManager` so that you don't even have to care ;) – Gaël J Aug 08 '21 at 16:22
  • Thanks a lot. That helps – NoScript07 Aug 09 '21 at 13:19

0 Answers0