2016-02-26 32 views
0

我有User類和BattleReportILogItem類。 這個類別(UserBattleReportILogItem)是@EntityJPA從ManyToMany中選擇,怎麼樣?

我不知道,如何編寫代碼從這個Entity中選擇。

我想從BattleReportILogItem中選擇setOfBattleLogs

User0..NBattleReportILogItem

USER:

@Entity 
    @Table(name = DomainConstant.TABLE_USER) 
    public class User implements Serializable { 

     @Id 
     @Column(name = DomainConstant.DOMAIN_USER_ID) 
     @GeneratedValue 
     private Long userId; 

     @ManyToMany(cascade = {CascadeType.ALL}) 
     @JoinTable(name = DomainConstant.VIEW_USER_BATTLE_LOGS, joinColumns = { 
      @JoinColumn(name = DomainConstant.DOMAIN_USER_ID)}, inverseJoinColumns = { 
      @JoinColumn(name = DomainConstant.DOMAIN_BATTLE_REPORT_ID)}) 
     private Set<BattleReportILogItem> setOfBattleLogs = new HashSet<>(); 

....(other stuff, get and set methods...) 

BattleReportILogItem

@Entity 
@Table(name = DomainConstant.TABLE_BATTLE_REPORT) 
public class BattleReportILogItem implements Serializable { 

    @Id 
    @GeneratedValue 
    @Column(name = DomainConstant.DOMAIN_BATTLE_REPORT_ID) 
    private Long BattleReportILogItemId; 

    @ManyToMany(mappedBy = "setOfBattleLogs") 
    private Set<User> setOfBattleLogs = new HashSet<>(); 

    ....(other stuff, get and set methods...) 

我試試

Query q = em.createQuery("select c1 \n" 
     + "from User c1 \n" 
     + "join c1.setOfBattleLogs c2 \n" 
     + "where c1.userId = :c1userId", User.class); 

...所以,這個代碼是錯誤的,我知道... :-(

你能一些身體幫我嗎?我在這個stackoverflow站點上讀了一些線程,但它不能幫我解決我的問題。

謝謝你的幫助!

回答

0

所以,這個代碼是錯誤的,我知道

不,這不是錯了,是什麼讓你覺得這是什麼?

你只需要選擇C2而不是C1的:

//I'll rename c1 to u and c2 to b to reduce confusion in the query 
select b from User u join u.setOfBattleLogs b where u.userId = :paramUserId 

當然,你再不能得到User實體的名單,但BattleReportILogItem實體的名單。

順便說一下,在你的BattleReportILogItem類中你有private Set<User> setOfBattleLogs = new HashSet<>(); - 我假設該集合應該被命名爲users或類似的東西。

你也可以交換實體查詢:

select b from BattleReportILogItem b join b.users u where u.userId = :paramUserId 
+0

親愛的托馬斯,感謝您的幫助和明確的答案!工作很好。 4分鐘後我會接受你的答覆。 – nustauos