Jpa / Hibernate request returns wrong result when before executing another request

I have a very strange case with jpa / hibernate.

I have 4 objects, something like this

entity County  has Set<City>
City has Set<CityRegion>
CityRegion has Set<House>

      

I have 2 requests in DAO (in 2 methods). I am using QueryDsl for JPA but it generates these 2 jpa requests.

select distinct county
from County county
  inner join fetch county.cities as city
  inner join fetch city.cityRegions as cityRegion
  inner join fetch cityRegion.houses as house
where city.id = ?1


    select distinct county
from County county
  inner join fetch county.cities as city
  inner join fetch city.cityRegions as cityRegion
  inner join fetch cityRegion.houses as house
where house.id = ?1

      

When I only call the second request from the service class, it works fine. But when I call the first request and then call the second (in the same service method), the second request returns the same (in this case, wrong) result as the first. And I can't find the house that id asks about. Also this house does not belong to this city.

In the log, the generated native sql looks correct and correct.

I don't have a second level cache. maybe there are some problems with transactions and first level cache?

UPDATE Actually it always returns the result of the first query, I change the order of the queries and now the second query again returns the same as the query of the first query. There seems to be some kind of cache. How do you run the query the first time and the second time hibernation returns the same result, is it possible? But I can see both SQL queries in the log.

UPDATE 2 The code looks something like this.

  @Service
    public class CountryService {

    @Autowired
    private CountryRepository  countryRepo;
     public CountryService(CountryRepository countryRepo){
       this.countryRepo = countryRepo
     } 

     public List<Country> getByFilter(int cityId, int houseId){
       List<Country> a = this.countryRepo.getByCity(cityId);
       List<Country> b this.countyRepo.getByHouseId(houseId);
       return merge(a, b);
     }
    }


    @Repository
    @Transactional
    public class CountryRepository {

     @PersistenceContext
      private EntityManager entityManager;

        public List<Country> getByCity(int id){}

        public List<Country> getByHouse(int id){}
    }

      

UPDATE 3 If I do entityManager.clear();

, it works great, I researched and found out that both dao methods use the same hibernate session. I think this leads to this problem. Myabe Do I need to somehow force spring and hibernate to create a new session for every method call?

Using spring boot project, jpa / hibernate. Thank.

+3


source to share





All Articles