Skip to content
Advertisement

Does @Transactional preserves the session open , if yes – why do I have 3 DB calls?

Here is my simple method – just returns DTOs

public List<DishResponseDTO> getAll() {
    List<Dish> dishlsit = dishRepository.findAll();
    return dishlsit.stream()
            .map(DishMapper::toDishResponseDTO)
            .collect(Collectors.toList());
}

I call it in @SpringBootTest with a @Transactional annotation.

@Test
@Transactional
public void get() {
    System.out.println(dishService.getAll());
    System.out.println(dishService.getAll());
    System.out.println(dishService.getAll());
}

Does it perform all calls in a single session? I though it does, because of the @Transactional, but the problem is that I have 3 calls to DB. I thought that Hibernate First level cache makes sure not to call the same objects with the same paremeters again in scope of a session.

Advertisement

Answer

Hibernate does indeed have the entity objects in the first level cache keyed by the primary key, but what you are doing with findAll is executing a query, which usually always has to go to the database. Hibernate has a second level cache (for entities) and a query cache though, which will allow you to avoid executing the query on the database irrespective of the session.

10 People found this is helpful
Advertisement