问题
I have very strange case with jpa/hibernate.
I have 4 entities , something like this
entity County has Set<City>
City has Set<CityRegion>
CityRegion has Set<House>
I have 2 queries in DAO(in 2 methods). I use QueryDsl for JPA, but it generates those 2 jpa queries.
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 call only second query from service class it works fine. But when I call first query and then call second (in same service method), second query returns same( in this case wrong) result as first one. And I cann't find house which is queried by id. Also that house does not belong to that city.
In log generated native sql looks fine and correct.
I don't have second level cache. maybe there is some problem with transactions and first level cache ?
UPDATE Actually it always return result from first query, I change the order of queries and now it second query again returns same as first query call. It seems there is like some cache. Like you run query first time and second time hibernate returns same result, is this possible ? But I can see both sql queries in log.
UPDATE 2 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 fine,
I investigated and find out that both dao methods use same hibernate session. I think this leads to this problem. Myabe I need to somehow force spring and hibernate to create new Session for each method call ?
Project use Spring boot , jpa/hibernate. Thanks.
来源:https://stackoverflow.com/questions/43909146/jpa-hibernate-query-return-wrong-result-when-before-it-executed-other-query