When I call EntityManager's update or remove method, I first need to make the entity managed by calling find(). But it means double trip to database.Am I doing it wrongly or is it the only way?
Asked
Active
Viewed 1,456 times
0
-
`EntityManager` has no method like `update()`. Please be clear with the term usage. Use `EntityManager#getReference()` before deleting an entity whenever possible. A merge operation is a different thing where you pass a detached or unmanaged entity to `EntityManager` to make it a managed entity. – Tiny Dec 29 '15 at 14:57
-
sorry for using wrong word...its merge. – Mandroid Dec 29 '15 at 15:00
2 Answers
0
I am not sure if i understand you correctly. But if you mean you have to do something like
Employee employee = em.find(Employee.class, 1);
em.getTransaction().begin();
em.remove(employee);
em.getTransaction().commit();
Then yes, you have to do it like that :)

Heady
- 935
- 3
- 10
- 23
0
To use merge
or remove
methods of 'EntityManager' you need to pass th entity object in the parameter.
You can also use native queries
(em.createNativeQuery
), which allows you to execute any request you want.
After all, JPA has a cache layer to prevent unnecessary requests to go all the way to the DB. When you call find(id)
, JPA will first try to retrieve it from cache if it is not modified since.
So, don't worry about that

ikken
- 563
- 4
- 15
-
1...but if it doesn't find one in persistent context then it would fetch it from DB.So if I want delete entity, then call to find would make a DB visit to fetch it and then calling delete() would make another call.If I don't call find() then delete doesn't do anything. Row still lies there in table.I am using OpenJPA. – Mandroid Dec 29 '15 at 15:03
-
-
Try using `entityManager.flush();` to force synchronize your persistentContext whith DB – ikken Dec 29 '15 at 15:11