0

I'm using SpringBoot 2.2.6 with JPA 2 and Hibernate 5 and I have the following problem.

I have a @Service similar to following one:

public class Service {
 @Autowired OtherService otherService;
 @Autowired SaveService saveService;

 public doIt() {
    Entity entity = otherService.findById(id) // retrieve the entities
    entity.getSubEntities().add(subEntity)    // should add a row to certain table (subentity is a 1:n relationship)
    saveService.update(entity);               // the row is added, I can see it on phisical DB
    entity = otherService.findById(id);          // the DTO subentity doesn't contain the row added
 }

}

public class OtherService {
  @Autowired JpaRepository jpaRepository;

  public Entity findById(Integer id) {
    return jpaRepository.findById(id);
  }
}

public class SaveService {
  @Autowired JpaRepository jpaRepository;

  public void update(Entity entity) {
    jpaRepository.save(entity);
  }
}

As I wrote in the comments, the first find extract an entity with a subEntity (1:n relationship) correctly loaded. The second row save a new line in the db and the third line retrieve the Entity again.

If I debugging the app, when I arrive to the third row I can see the new line added to the DB but when I fire the find the entity doesn't have the subentity (a list) correctly loaded.. It has one element less than the DB..

Why does this happen? I remove the @Transactional annotation everywhere to avoid similar error (the order of query and so on..)

Thank you.

CoderJammer
  • 599
  • 3
  • 8
  • 27
  • Does this answer your question? [Changes not reflected after "refreshing" entity with Spring JPA](https://stackoverflow.com/questions/50600539/changes-not-reflected-after-refreshing-entity-with-spring-jpa) – Jens Schauder Mar 10 '21 at 08:28
  • There are many other similar questions that revolve around the same basic problem: https://stackoverflow.com/questions/36581885/jpa-refresh-entity https://stackoverflow.com/questions/62147033/force-jpa-to-reload-entity-from-database https://stackoverflow.com/questions/38974925/hibernate-does-not-refresh-entity-childs-completely – Jens Schauder Mar 10 '21 at 08:30

0 Answers0