2012-03-20 142 views
0

目標是檢索已向特定用戶(當前登錄用戶)發送消息的所有用戶(而不是消息),或已收到來自此用戶的消息(即使他們沒有還沒回復)。我已經嘗試了很多查詢,但無濟於事。 (我有登錄用戶的ID)。JPA/Hibernate加入查詢

你有什麼想法嗎?我假設我需要加入消息& RegisteredUser類,但不知道它是如何工作的,因爲消息具有'發送者'&'接收者',這使得查詢有點複雜。

RegisteredUser類(不必消息的引用):

@Entity 
@Table(name = "USER") 
public class RegisteredUser implements Serializable { 

    @Id 
    @GeneratedValue(strategy = GenerationType.IDENTITY) 
    private int id; 

消息類別:

@Entity 
@Table(name = "MESSAGE") 
public class Message implements Serializable { 

    @Id 
    @GeneratedValue(strategy = GenerationType.IDENTITY) 
    int id; 

    @ManyToOne 
    @JoinColumn(name = "receiverId") 
    RegisteredUser receiver; 

    @ManyToOne 
    @JoinColumn(name = "senderId") 
    RegisteredUser sender; 

我使用JPA 2.0和休眠3.5.6。

謝謝!

//編輯 - ?解決方案,這要歸功於安德烈

"select distinct u from RegisteredUser u where u in (select m1.sender from Message m1 join m1.receiver r where r.id = " + user.getId() + ") or u in (select m2.receiver from Message m2 join m2.sender s where s.id = " + user.getId() + ")" 

回答

1
select distinct u from RegisteredUser u where 
u in (select m1.sender from Message m1 join m1.receiver r where r.id = " + user.getId() + ") or 
u in (select m2.receiver from Message m2 join m2.sender s where s.id = " + user.getId() + ")" 
+0

什麼會的1的值&2是什麼?假設通過getId()檢索登錄用戶的ID,則將?1或/和?2設置爲getId()將返回登錄用戶,而不是與他通信的用戶列表或與他通信的用戶列表。 – Vladimir 2012-03-20 14:14:55

+0

基本上,我需要返回發件人,如果receiver.id = getid()和接收者時sender.id = getId() – Vladimir 2012-03-20 14:29:53

+0

這樣的事情(不知道它是否會工作,需要測試當我' (選擇m1.sender from Message m1 join m1.receiver r其中r.id =「+ getId()+」)或u in(從Message中選擇m2.receiver m2 join m2.sender s where s.id =「+ getId()+」)「 – Vladimir 2012-03-20 14:46:02