【问题标题】:Hibernate return result is different direct queryHibernate返回结果不同直接查询
【发布时间】:2015-08-04 08:46:09
【问题描述】:

我正在使用 Hibernate createcriteria 来连接几个表并从数据库中查询数据。我发现结果返回与直接从 SQL 客户端使用 hibernate 生成的 SQL 语句查询的结果不同。 Hibernate 返回的结果不仅仅是直接查询。 我只是想知道为什么会发生这种情况?

下面是 Hibernate createcriteria 生成的 SQL 语句。我已将值替换为“?”语句中的占位符。

select this_.mrctBizId as mrctBizI1_5_13_, this_.name as 
 name11_5_13_, 
 from go.go_mrct_business this_ 
 inner join go.go_location location3_ on this_.LocId=location3_.locId 
 inner join go.go_state state4_ on location3_.StateId=state4_.stateId 
 inner join go.go_country country5_ on state4_.CountryId=country5_.countryId 
 left outer join go.go_mrct_off_date holiday7_ on this_.mrctBizId=holiday7_.MrctBizId and ( (holiday7_.startDt<='2015-05-23' and holiday7_.endDt>='2015-05-23') ) 
left outer join go.go_mrct_business gomrctbusi13_ on holiday7_.MrctBizId=gomrctbusi13_.mrctBizId 
left outer join go.go_mrct_off_day offday6_ on this_.mrctBizId=offday6_.MrctBizId and ( offday6_.offDay=7 ) 
left outer join go.go_mrct_business gomrctbusi15_ on offday6_.MrctBizId=gomrctbusi15_.mrctBizId 
inner join go.go_service service1_ on this_.mrctBizId=service1_.MrctBizId 
inner join go.go_category gocategory2_ on service1_.CatId=gocategory2_.catId 
left outer join go.go_mrct_business gomrctbusi20_ on service1_.MrctBizId=gomrctbusi20_.mrctBizId     
where offday6_.MrctBizId is null 
and holiday7_.MrctBizId is null 
and this_.enabled=true 
and service1_.enabled=true 
and gocategory2_.catId=11 
and country5_.countryId=1 
and state4_.stateId=2 
and location3_.locId=6 
and this_.bizStartTime<=CAST('10:10:00' AS time) 
and this_.bizEndTime>=CAST('10:10:00' AS time) ;

【问题讨论】:

  • 请添加更多详细信息,例如您的“直接”sql 查询和条件查询。
  • 上面的SQL语句是hibernate createCriteria生成的查询,我也是用这个SQL语句直接通过SQL客户端查询,但是返回的结果不同

标签: hibernate


【解决方案1】:

你不能做这样的比较,因为 Hibernate 有一个一级缓存(会话),如果你在这个缓存中修改了对象,它们将被混合到结果中具有相同 id 的那些对象。这是 Hibernate 保证的对象可重复读取背后的概念。

直接 SQL 会绕过 Hibernate 的缓存,因此结果不会反映 Hibernate 会话中的任何本地更改。

如果您真的想进行此比较,请确保您有一个干净的会话,并且您正在查询的表没有发生其他更新。

【讨论】:

  • 即使我通过 JUnit 测试来测试它?我用JUnit试过了,结果还是一样。
  • 是的,语义不会改变它的调用方式。您可以确保您的会话是清晰的,并且这是在会话中运行的唯一查询。但我仍然不建议做这样的比较。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-24
  • 2013-08-13
  • 2011-11-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多