如何用sql创建嵌套选择?

时间:2015-06-08 14:30:32

标签: java sql jpa

我想选择由自定义层次结构绑定的所有实体:

@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吗?如果是,怎么样?

2 个答案:

答案 0 :(得分:2)

尝试这样的事情:

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

答案 1 :(得分:1)

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

JPQL查询(需要一个名为EntityManager的{​​{1}}变量

em

SQL等价物:

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();
}