Hibernate does not update entities

I am using Hibernate 5.1.0.Final. My main methods of the GenericDAO class:

 public T save(T entity) { entityManager.getTransaction().begin(); entityManager.persist(entity); entityManager.getTransaction().commit(); } public T find(Long entityId) { T e = (T) entityManager.find(type, entityId); entityManager.refresh(e); return e; } 

I have an Item object that contains List<Image> images .

 @Entity @Table(name="item") public class Item extends GenericEntity { @Column(name="title") String title; @OneToMany(fetch = FetchType.LAZY, mappedBy = "item", cascade = {CascadeType.ALL}, orphanRemoval = true) @NotFound(action = NotFoundAction.IGNORE) List<Image> images; @Version @Temporal(TemporalType.TIMESTAMP) @Column(name="version") Date version; } @Entity @Table(name="image") public class Image extends GenericEntity { @ManyToOne @JoinColumn(name="item") Item item; @Column(name="image_name") String imageName; } 

First I load the Item using the genericDAO.find(id) method - it contains an updated list of images. Then I load the Item with the same identifier into another REST method, which removes old images and adds new ones, changes the title. Later, if I try to reload the Item using genericDAO.find(id) in the first REST method, I get outdated images - they will not be re-selected until the Item heading is restored correctly.

How to get a fully updated entity with its children from the database?

+2
java rest hibernate jpa entitymanager
Aug 16 '16 at 12:25
source share
1 answer

Your way of caching your entityManagers correct, as in the request , but it has side effects, as you may notice.
You are using level 1 cache for sleep mode.
Why shouldn't I use a separate instance of entityManager per transaction?
It is not expensive to create an instance of EntityManager at the request of the user.

If you want to cache entityManager, entityManager.refresβ€Œβ€‹h(e) seems insufficient because it doesn't seem to clear the level 1 cache. So, if you want to clear the first level cache, try clearing the persistenceContext . There is no guarantee, but you can try: entityManager.clear()

Personally, I prefer the solution using a unique instance of entityManager per transaction. It is a cheap and clear design.

+1
Aug 16 '16 at 13:54 on
source share



All Articles