hibernate 的hql查询语句中使用fetch的注意点

3 篇文章 0 订阅
1 篇文章 0 订阅

hibernate 的hql中使用fetch 可以取消lazy load,有效减少发出的sql查询语句(多sql语句意味着多次访问数据库,加大连接次数,降低使用效率)。提高数据库的访问效率。但是在使用fetch的问题中仍可能会出现一些问题:这里主要有三个model   :User(one)<-------------->(many)UserRole(many)<---------------------->(one) Role,简单的说 这里user和role是many2many的关系,通过一个userRole转换为两个many2One的关系。

这里有以下几个方法:

public List<Role> listUserRoles(int userId) 



这个方法要通过userId关联UserRole对象查找Role对象。这里可以使用" select ur.role from UserRole ur where ur.user.id = ?"直接查询,不使用left join可以得到结果,但是如果使用

"select ur.role fromUserRoleur left join  ur.role r left join fetch ur.user u  where u.id = ?";  这时候会发现运行时出现

org.hibernate.QueryException: query specified join fetching, but the owner of the fetched association was not present in the select list [FromElement{explicit,not a collection join,fetch join,fetch non-lazy properties,
classAlias=r,role=null,tableName=t_role,tableAlias=role1_,origin=t_user_role userrole0_,columns={userrole0_.r_id ,className=org.konghao.cms.model.Role}}] [select ur.role from org.konghao.cms.model.UserRole ur left join fetch ur.role r left join fetch ur.user u  where u.id = ?]
	

错误。如果将fetch去除则不会出现这样的问题。这里主要的原因参考

http://zhan.renren.com/itsavingdebug?gid=3602888498024713423&checked=true

的说明。

简单的说from的左右两边如果不是同一个类Select A.B from A。这里不能使用fetch。如果from的左右两边是同一个类:select A from A  //当然这里的select A可以去除。这样的形式的话就可以使用fetch解除lazy load的问题。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值