请考虑以下模式
@Entity
Class employee{
@OneToMany()
List<employee> manaagedEmps;
@OneToOne
employee manager;
}如何编写一个查询来获取某个经理的所有受管员工,直接(managedEmps列表)和间接(由受管员工管理)。
发布于 2014-05-02 23:44:52
JPA似乎不支持递归查询。最近,我通过添加ltree (postgresql)类型的"path“字段解决了smilar问题。Path是通过在父节点的path中添加以点分隔的id来生成的,根节点的path就是id。通过该字段,您可以查询某些节点(经理)的子树(直接和间接员工):
SELECT * FROM nodes WHERE path ~ '*.42.*{1,}'; /* for path of type ltree */
SELECT * FROM nodes WHERE path LIKE '%.42.%'; /* for path of type varchar */下面的JPQL查询返回id为2的员工的subs的平面列表。
List<Employee> subs = em.createQuery(
"SELECT e FROM Employee e LEFT JOIN FETCH e.subs WHERE e.path LIKE '%.' || ?1 || '.%'",
Employee.class
).setParameter(1, '2').getResultList();发布于 2014-05-02 22:33:17
//Returns a list of the managed employee of the manager with the specified ID.
@NamedQuery(name="queryName", query="SELECT p.managedEmps FROM employee p WHERE p.manager.uuid = :uuid")发布于 2018-12-25 23:42:49
我在这里使用postgresql。
我是通过原生查询实现的,如下所示:
假设以下实体
@Entity
@Table(name = "employee")
public class Employee {
@Id
private Long id;
@ManyToOne
@JoinColumn(name = "parent_id")
private Employee parent;
}现在,可以使用以下查询来递归地获取一个管理器下的所有childs和子childs:
public interface IEmployeeRepository extends JpaRepository<Employee, Long> {
@Query(value = "with recursive subordinates as ("
+ " select e1.id as id, e1.parent_id as parent from employee e1 where e1.parent_id = :parentId"
+ " union"
+ " select e2.id, e2.parent_id from employee e2"
+ " inner join subordinates s on (s.id = e2.parent_id)"
+ " ) select * from subordinates", nativeQuery = true)
Collection<Employee2> getChilds(@Param("parentId") Long parentId);
public static interface Employee2 {
Long getId();
Long getParent();
}
}现在,您必须将此结果集合转换为服务层中的List。就这样。
参考资料:postgres recursive queries Jpa Projections to get result
希望这能有所帮助。
https://stackoverflow.com/questions/23430130
复制相似问题