Home > front end >  why when we use getReference() with remove(), getReference() hits the Database and causes a SELECT s
why when we use getReference() with remove(), getReference() hits the Database and causes a SELECT s

Time:04-22

I have a question about getReference(). why when we use getReference() with remove(), getReference() hits the Database and causes a SELECT statement?

I expect in the this code, we have just 2 statement: one INSERT because of persist() and one DELETE because of remove().

we know that getReference() makes a proxy object and doesn't hit the Database until it need. then why we have a SELECT in our output?

public class RemoveThirdTestMain {

    static EntityManagerFactory emf = Persistence.createEntityManagerFactory("pu");

    public static void main(String[] args) {
        RemoveThirdTestMain remThird = new RemoveThirdTestMain();
        remThird.removeManagedObject2();
    }

    private void removeManagedObject2() {

        EntityManager entityManager = emf.createEntityManager();
        entityManager.getTransaction().begin(); // begin tx.

        Person p1 = new Person("Mo", "As");

        entityManager.persist(p1); // will cause a INSERT.

        entityManager.getTransaction().commit(); // commit tx.
        entityManager.close();

        entityManager = emf.createEntityManager();
        entityManager.getTransaction().begin(); // begin tx.


        Person theP1 = entityManager.getReference(Person.class, 1L); 

        entityManager.remove(theP1); // will cause a DELETE.

        entityManager.getTransaction().commit();
        entityManager.close();

    }
}

and this is my Output:

Hibernate: insert into Person (firstName, lastName) values (?, ?)
Hibernate: select person0_.id as id1_2_0_, person0_.firstName as firstnam2_2_0_, person0_.lastName as lastname3_2_0_ from Person person0_ where person0_.id=?
Hibernate: delete from Person where id=?

CodePudding user response:

Because what you trying to delete is a proxy so the persistence context must be sure that that entity exists in database,because it have to load that entity which will make it in managed state then delete it from database and change its state to removed and like that the database and the persistence context stay in sync

  • Related