Hibernate从表联接中选择一个表

时间:2019-05-09 16:26:22

标签: mysql hibernate

您好,我有2个表具有多对多关系:

用户实体:

Entity
@Table(name = "user_user")
@Where(clause = "is_delete <> 'Y'")
public class User extends CommonColumn {
    @Id
    @GeneratedValue(strategy= GenerationType.AUTO)
    @Getter @Setter
    private long id;

    @Column(name="fullname")
    @Getter @Setter
    private String fullName;    

    @Type(type = "yes_no")
    @Column(name="is_active")
    @SortableField
    @Field(termVector = TermVector.YES)
    @Getter @Setter
    private boolean isActive;

    @Type(type = "yes_no")
    @Column(name="is_delete")
    @Getter @Setter
    private boolean isDeleted;

    @ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    @JoinTable(name = UserConstants.REFERENCE_GROUP_USER,
    joinColumns = {@JoinColumn(name = "user_id")},
    inverseJoinColumns = {@JoinColumn(name = "user_group_id")}
    )
    @JsonBackReference
    @Getter @Setter
    List<Group> groups = new ArrayList<Group>();

和用户组实体:

@Entity
@Table(name="user_group")
public class Group extends CommonColumn {

    @Id
    @GeneratedValue(strategy= GenerationType.AUTO)
    @Getter @Setter
    private Long id;

    @Column(name="group_name")
    @Getter @Setter
    private String groupName;

    @Type(type = "yes_no")
    @Column(name="is_active")
    @Getter @Setter
    private boolean isActive;

    @Type(type = "yes_no")
    @Column(name="is_deleted")
    @Getter @Setter
    private boolean isDeleted;

    @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    @JoinTable(name = UserConstants.REFERENCE_GROUP_USER,
    joinColumns = {@JoinColumn(name = "user_group_id")},
    inverseJoinColumns = {@JoinColumn(name = "user_id")}
    )
    @JsonBackReference
    @Getter @Setter
    List<User> users = new ArrayList<User>();
}

我只选择那些具有is_active = true用户的用户组。我尝试过:

@Query(value = "SELECT ug from User u INNER JOIN user_group_user ugu ON u.id = ugu.user_id\r\n" + 
            "INNER JOIN user_group ug ON ugu.user_group_id = ug.id WHERE u.is_active = 'Y' GROUP BY\r\n" + 
            "ug.group_name ORDER BY ug.group_name ASC", nativeQuery = true)
    List<Group> findLinkedUserGroups();

但是我收到错误消息“字段列表中的未知列'ug'”

请帮助。非常感谢。

0 个答案:

没有答案