2015-06-08 121 views
2

我想选择由一个自定义的层次结构并列的所有实体:如何用sql创建嵌套选择?

@Entity 
class Employee { 
    @Id 
    private long id; 

    @ManyToOne 
    private Company company; 
} 

@Entity 
class Company { 
    @Id 
    private long id; 

    @ManyToOne 
    private LeisureGroup leisureGroup; 
} 

@Entity 
class LeisureGroup { 
    @Id 
    private long id; 
} 

//选择属于LeisureGroup

Select * from company where leisureGroupId = '123' 

TODO所有的公司:我怎样才能选择属于所有员工到LeisureGroup(由公司参考)?我必须在这里使用joins吗?如果是,如何?

+0

如果你不使用SQL要通过JPA查询,您使用JPQL(Java持久性查询语言)或HQL(Hibernate查询语言) – Tobb

回答

1

如果您想通过JPA查询,您使用JPQL(Java持久性查询语言)或HQL(Hibernate查询语言)(用于Hibernate用户),则不使用SQL。

JPQL查询(需要EntityManager变量称为em

public List<Employee> findEmployeesInLeisureGroup(final Integer leisureGroupId) { 
    final TypedQuery<Employee> query = 
     em.createQuery("select e " + 
         "from Employee e join e.company c join c.leisureGroup l " + 
         "where l.id = :leisureGroupId", Employee.class); 
    query.setParameter("leisureGroupId", leisureGroupId); 
    return query.getResultList(); 
} 

SQL相当于:

select * from Employee 
where company_id in (select id from Company where leisureGroup_id = 123); 
+0

这没有奏效(“where语法错误”)。 – membersound

+0

我在这里直接在StackOverflow中编程,不能保证它实际上能够工作:p我无法真正理解为什么它不起作用,但至少你有一个加入JPQL的例子。另外,不要指望将它作为SQL运行,这是一个JPA查询。 – Tobb

+0

只有当subselect返回一行/一个结果时,你的sql才会有效。但大多会有多个公司分配到同一个休闲组... – membersound

2

尝试这样的事:

Select e from Employee e where e.company.id= (select c.id from Company c where c. leisureGroup.id=:id 
+0

我想选择所有员工,而不是公司! – membersound

+0

检查更新后的代码 –

+0

如果只有一个'company'分配给'leisuregroup',这将起作用。但对于指定的2+公司,将返回“结果有多行”。但是由于@ ManyToOne的原因,这种情况大多会发生。 – membersound