Hibernate执行count别名的投影

时间:2016-05-09 11:12:52

标签: java hibernate subquery projection

这是我的代码:

   class A{
     Integer id
     String name
     Set<B> bs;

     //Getters and setters
}

class B{
     Integer id;
     A a;

     //Getters and setters
}

我需要做一个咨询来获取A的所有行,并且对于每一行需要知道许多B对A的引用。

我有SQL查询,但我不知道如何使用Java中的hibernate

简化查询:

select
    a.ID as y0_,
    ( select count(*) from 
        B b 
        where b.c47=a.ID 
        and b.FDL='N' 
        ) as count,
from
    A a 
inner join
    C c 
        on a.operario=c.ID 
where
    a.DID=2
    and a.FDL='N'

提前致谢

1 个答案:

答案 0 :(得分:0)

@Entity
@Table(name = "a_table")
class A
{
    @Id
    @GeneratedValue
    Integer id;

    @Column 
    String name;

    @OneToMany(mappedBy = "a")
    Set<B> bs;

     //Getters and setters
}

@Entity
@Table(name = "b_table")
class B
{
    @Id
    @GeneratedValue
    Integer id;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "a_id")
    A a;

     //Getters and setters
}

HQL:

select a.id, count(bs)
from A a
left join a.bs bs
inner join a.c c
where 
    a.id = 2 
    and a.FDL='N'
    and bs.FDL='N'