Jpa / Hibernate查询在执行其他查询之前返回错误的结果

时间:2017-05-11 07:31:00

标签: java spring hibernate jpa querydsl

我的jpa / hibernate非常奇怪。

我有4个实体,类似这样的

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

我在DAO中有2个查询(在2种方法中)。我将QueryDsl用于JPA,但它会生成这2个jpa查询。

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

当我只从服务类调用第二个查询时,它工作正常。但是当我调用第一个查询然后调用第二个(在相同的服务方法中)时,第二个查询返回与第一个相同的结果(在这种情况下是错误的)。我无法找到被id查询的房子。那所房子也不属于那个城市。

在日志中生成的本机sql看起来很好而且正确。

我没有二级缓存。也许交易和第一级缓存存在一些问题?

UPDATE 实际上它始终返回第一个查询的结果,我更改查询的顺序,现在第二个查询再次返回与第一个查询调用相同的结果。似乎有一些缓存。就像你第一次运行查询和第二次hibernate返回相同的结果一样,这可能吗?但是我可以在日志中看到两个sql查询。

更新2 代码看起来像这样

  @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){}
    }

更新3 如果我做entityManager.clear();它工作正常, 我调查并发现两个dao方法都使用相同的hibernate会话。我认为这会导致这个问题。 Myabe我需要以某种方式强制spring和hibernate为每个方法调用创建新的Session?

项目使用Spring启动,jpa / hibernate。感谢。

0 个答案:

没有答案
相关问题