Is there any reasons to call entityManager.flush() right after the manager was created (JPA, Hibernate)

I am following Hibernate video lesson, and there were shown this code:

public class Main {

    private static EntityManagerFactory entityManagerFactory;

    public  static void main(String[] args)
    {
        entityManagerFactory = Persistence.createEntityManagerFactory("org.hibernate.tutorial.jpa");

        addEntities("Client1","Bank1");

        entityManagerFactory.close();
    }

    private static void addEntities(String clientName, String BankName)
    {
        Client client = new Client();
        client.setName(clientName);

        Bank bank = new Bank();
        bank.setName(BankName);

        EntityManager entityManager = entityManagerFactory.createEntityManager();
        entityManager.getTransaction().begin();
        entityManager.flush();

        entityManager.persist(client);
        entityManager.persist(bank);

        entityManager.getTransaction().commit();
    }
}

And I am concerned about this part of code:

EntityManager entityManager = entityManagerFactory.createEntityManager();
        entityManager.getTransaction().begin();
        entityManager.flush();

We generated new EntityManager. As I understand, it has empty Persistence context, as it was just created, isn't it ? In that case,why do we call flush() method. What is the purpose ?

Upvotes: 0

Views: 161

Answers (1)

Narendra
Narendra

Reputation: 382

EntityManager#flush actually pushes the changes to the database immediately.

In the above code, a transaction has just started entityManager.getTransaction().begin() and there is no change that needs to be pushed to the database so I would say it is not needed there. You may remove it.

Anyways, it is a good practice to let entitymanager take care of when to push the data changes to the database instead of manually taking control over it. There could be use case when different applications or threads are trying to access the same data at same time.

Upvotes: 1

Related Questions