2016-08-12 75 views
0

與HQL工作,在這個簡化的場景:HQL查詢與LEFT JOIN和WHERE不給結果

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像(:查詢)

這些都是我的表:

用戶

@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

回答

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) ";

+0

謝謝,但我得到相同 –

+0

你能告訴我2表,用戶和朋友? –

+0

是的,我編輯了我的問題 –