使用LEFT JOIN的HQL查询和WHERE不给出结果

时间:2016-08-12 02:51:33

标签: java hibernate hql

在这个简化的场景中使用HQL:

String query =  "SELECT new CustomUser(" +
                "user.userID AS id," +
                "user.username AS username)" +
                "FROM User AS user" +
                " LEFT JOIN user.friends as friend " +
                " where user.username like (:query)" +
                " OR " +
                " friend.username like (:query) ";

这只回馈那些至少有一个朋友的用户,但我想让用户接受一个条件,除了和朋友在一起之外。

  • 由于域要求而使用动态实例化
  • 我注意到,如果联接表上没有条件( friend.username like(:query)),它会给所有用户,有或有朋友。

这些是我的表格:

用户

@Id...
protected Integer userID;

@Column(name = "username")
private String username;

@OneToMany(mappedBy = "user", cascade = CascadeType.REMOVE)
private List<Friend> friends;

朋友

    @Id
    private Integer friendID;

    @Column(name = "username")
    private String username;

    @ManyToOne(cascade = CascadeType.DETACH)
    @JoinColumn(name="userid")
    private User user;
  • 注意:它的工作方式与原生SQL上的预期相同

1 个答案:

答案 0 :(得分:0)

您可以尝试此查询 String query = "SELECT new CustomUser(" + "user.userID AS id," + "user.username AS username)" + "FROM User AS user" + " LEFT OUTER JOIN user.friends as friend " + " where user.username like (:query)" + " OR " + " friend.username like (:query) ";