【问题标题】:JPA select from ManyToMany, how?JPA 从 ManyToMany 中选择,如何?
【发布时间】:2016-02-26 23:28:04
【问题描述】:

我有User 类和BattleReportILogItem 类。 这个类(User,BattleReportILogItem)是@Entity。

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

我想从BattleReportILogItem类中选择setOfBattleLogs。

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

感谢您的帮助!

【问题讨论】:

    标签: java jpa


    【解决方案1】:

    所以,这段代码是错误的,我知道

    不,这不是那错,是什么让你认为它是?

    你只需要选择 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&lt;User&gt; setOfBattleLogs = new HashSet&lt;&gt;(); - 我认为该集合应该命名为 users 或类似的名称。

    您还可以交换查询中的实体:

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

    【讨论】:

    • 亲爱的 Thomas,感谢您的帮助和明确的回答!干得好。我会在 4 分钟后接受您的回复。
    猜你喜欢
    • 2017-01-30
    • 2021-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-31
    相关资源
    最近更新 更多