Java Jpa/Hibernate查询在执行其他查询之前返回错误的结果
我对jpa/hibernate有一个非常奇怪的例子 我有4个实体,类似这样的Java Jpa/Hibernate查询在执行其他查询之前返回错误的结果,java,spring,hibernate,jpa,querydsl,Java,Spring,Hibernate,Jpa,Querydsl,我对jpa/hibernate有一个非常奇怪的例子 我有4个实体,类似这样的 entity County has Set<City> City has Set<CityRegion> CityRegion has Set<House> @Service public class CountryService { @Autowired private CountryRepository countryRepo; pu
entity County has Set<City>
City has Set<CityRegion>
CityRegion has Set<House>
@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){}
}
当我只调用服务类中的第二个查询时,它可以正常工作。但当我调用第一个查询,然后调用第二个查询(在相同的服务方法中)时,第二个查询返回和第一个查询相同的结果(在本例中是错误的)。我找不到id查询的房子,而且那个房子不属于那个城市
在日志中生成的本机sql看起来很好并且正确
我没有二级缓存。事务和一级缓存可能存在一些问题
更新实际上,它总是从第一次查询返回结果,我更改了查询的顺序,现在第二次查询再次返回与第一次查询调用相同的结果。好像有一些缓存。就像第一次运行查询,第二次hibernate返回相同的结果一样,这可能吗?但我可以在日志中看到这两个sql查询
更新2
代码看起来像这样
entity County has Set<City>
City has Set<CityRegion>
CityRegion has Set<House>
@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){}
}
@服务
公共服务{
@自动连线
私人回购;
公共国家服务(countryRepo){
this.countryRepo=countryRepo
}
公共列表getByFilter(int cityId、int houseId){
列表a=this.countryRepo.getByCity(cityId);
列表b this.countyRepo.getByHouseId(houseId);
返回合并(a,b);
}
}
@存储库
@交易的
公共类存储库{
@持久上下文
私人实体管理者实体管理者;
公共列表getByCity(int id){}
公共列表getByHouse(int id){}
}
更新3
如果我执行entityManager.clear()代码>工作正常,
我调查发现两种dao方法使用相同的hibernate会话。我认为这导致了这个问题。Myabe我需要强制spring和hibernate为每个方法调用创建新会话吗
项目使用SpringBoot,jpa/hibernate。谢谢。请将您的服务类与您的DAO一起分享。您为什么不在服务中以您的方式返回任何内容?您能否更正您的代码,以便它可以编译?有很多错误让你的帖子很难理解:No return,getByHouse/getByHouseIdSorry这不是一个真正的代码。我不能发布真实的代码:(我认为这里的主要问题是,一个方法调用如何更改另一个方法的返回结果,因为如果它们单独调用,这两个方法都可以正常工作。即使它不是真实的代码,您也应该提供一个可以编译的代码。如果您想得到一个有用的答案,这是主要规则: