elements hql

需求:

对象之间是多对多,需要一方查询另一方,而条件是一方除了满足自身的where限制意外,还要受关联的多的一方的限制。

例子1:

public class A extends BaseEntity{  
    private Set<C> c;  
    private static final long serialVersionUID = 1L;
}

A中有对C的关联many-to-many,

现在要根据c中的属性name来查询A的信息。

用sql是可以写的,现在介绍hql写法。

用到了in 和 in elements这两个不同的用法

in elements 是专门针对set集合的。

最简单例子hql如下:

select distinct afrom A a,C c where c.name like '%"+value+"%'

and a in  elements(c.conPurchaseInfo);

例子2:

User和Role是多对多的关系,User和HandMedical是一对多的关系,现在根据角色名得到有HandMedical的用户:

String hql="from User u " +
    "where u in(select elements(r.users) from Role r where r.name=?) " +
    "and u.id in (select h.user.id from HandMedical h)";

elements(r.users)的意思是:在多对多关系中,即从Role和User的中间表中得到所有的用户。其中users是Role中设置的User的set集合属性。

select elements(r.users) from Role r where r.name=?的意思是:从Role中表中得到name是?的用户。

例子3:

在传递索引和元素给集合时(elements and indices函数)和传递子查询的结果集时,SQL函数any, some, all, exists, in都是被支持的:

可编写如下Hql 语句完成查询:

HQL代码 
select Blog 
    from Blog, Book   
    where Blog.author in elements(Book.authors)   
        and Book.id=?   
对应的Sql近似如下:
Sql代码
 select  blog.*   
   from  blog, book   
    where  (blog.author  in  ( select  author.authorid  
            from  book_author   
            where  book.id=book_author.bookid))   
        and  book.id=?  
 

 

猜你喜欢

转载自minyongcheng.iteye.com/blog/1931400
HQL