简体   繁体   English

使用左联接从子表到父表的Hibernate HQL

[英]Hibernate HQL from child to parent table using left join

In the model there are two tables: person , role 在模型中,有两个表:person,role

PersonRole java class models the N:M relationship. PersonRole Java类为N:M关系建模。 It has two @ManyToOne attributes: 它具有两个@ManyToOne属性:
Person person, Role role 人人物,角色角色

I have one HQL query to retrieve all users belonging to a role: 我有一个HQL查询来检索属于某个角色的所有用户:

select role.name, person.name from PersonRole pr join pr.person join pr.role

Need to do the other way round: all the roles for a person. 需要反过来:一个人的所有角色。 But if a person has no roles still need to retrieve the person (left join) 但是,如果一个人没有角色,仍然需要检索该人(左联接)

select person.name, ro.le.name from PersonRole pr join pr.person join pr.role

This is not working as the main entity is PersonRole and returns only users with roles. 这不起作用,因为主要实体是PersonRole,并且仅返回具有角色的用户。 Dont know how to start the join from Person and go to the optional roles if there is no attribute in the Person entity to reference the role. 如果Person实体中没有用于引用角色的属性,则不知道如何从Person开始联接并转到可选角色。

how is the best way to do? 最好的方法是怎么做?

UPDATED ANSWER 更新的答案

Try this: 尝试这个:

Put in your Person class a property as follow: 在您的Person类中放置一个属性,如下所示:

List<Role> lstRole;

In this way when you'll write your query: 这样,当您编写查询时:

SELECT P FROM Person P

you'll get for each Person a list af associated roles. 您将获得每个人相关角色的列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM