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

来源:互联网 发布:mac如何切换输入法 编辑:程序博客网 时间:2024/05/20 23:31

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的问题。

原创粉丝点击