JPA从ManyToMany中选择,如何?

时间:2016-02-26 15:18:49

标签: java jpa

我有User课程和BattleReportILogItem课程。 此课程(UserBattleReportILogItem)为@Entity

我不知道,如何编写代码来从Entity中选择。

我希望从课程setOfBattleLogs中选择BattleReportILogItem

User 0..N BattleReportILogItem

用户:

    @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网站上读了一些帖子,但它并没有帮我解决我的问题。

感谢您的帮助!

1 个答案:

答案 0 :(得分: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