【问题标题】:JPA EntityGraph DISTINCT with Parameter results in cartesian product带有参数的 JPA EntityGraph DISTINCT 导致笛卡尔积
【发布时间】:2019-01-28 13:24:28
【问题描述】:

2 我有一个具有 4 个 1:n 关系的实体

@Entity
@Table(name="REPORT_MESSAGE")
@NamedEntityGraph(name=ReportMessage.GRAPH_ALL, attributeNodes= {@NamedAttributeNode("reportEvents"), @NamedAttributeNode("reportLabels"), @NamedAttributeNode("reportReceivers"), @NamedAttributeNode("reportSenders")})
public class ReportMessage implements Serializable {

    @Id
    @Column(name="REPORT_MESSAGE_ID")
    private Long reportMessageId;

    //bi-directional many-to-one association to ReportEvent
    @OneToMany(mappedBy="reportMessage")
    private List<ReportEvent> reportEvents;

    //bi-directional many-to-one association to ReportLabel
    @OneToMany(mappedBy="reportMessage")
    private Set<ReportLabel> reportLabels;

    //bi-directional many-to-one association to ReportReceiver
    @OneToMany(mappedBy="reportMessage")
    private Set<ReportReceiver> reportReceivers;

    //bi-directional many-to-one association to ReportSender
    @OneToMany(mappedBy="reportMessage")
    private Set<ReportSender> reportSenders;

我想使用实体图进行快速获取

@Override
public List<ReportMessage> findAllEagerly() {
    EntityGraph<?> graph = em.createEntityGraph(ReportMessage.GRAPH_ALL);
    List<ReportMessage> reportMessages = em.createQuery("SELECT DISTINCT r FROM ReportMessage r")
            .setHint("javax.persistence.loadgraph", graph)
            .getResultList();
    return reportMessages;
}

此方法按预期工作:我在数据库中有 8 个条目,它返回 8 个 ReportMessage 但是,当我在查询中添加参数时,我得到了笛卡尔积:

@Override
public List<ReportMessage> findForMessagidEagerly(String messageid) {
    EntityGraph<?> graph = em.createEntityGraph(ReportMessage.GRAPH_ALL);
    Query query = em.createQuery("SELECT DISTINCT r  FROM ReportMessage r WHERE r.messageid=:messageid")
            .setHint("javax.persistence.loadgraph", graph);
    query.setParameter(ReportMessage.PARAM_MSG_ID, messageid);
    List<ReportMessage> messages = query.getResultList();

    return messages;
    }

我希望得到 1 个 ReportMessage 但得到 84 个。使用命名查询我得到相同的结果。怎么回事?

【问题讨论】:

  • 您如何查看调用的 SQL 并根据该证据发表您的意见?

标签: hibernate jpa parameters cartesian-product entitygraph


【解决方案1】:

问题是由双向关系引起的。更改为单向关系后,代码按预期工作。 但是,有人知道我的原始代码中是否存在错误,或者这是休眠还是 JPA 中未指定?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-29
    • 1970-01-01
    • 2017-08-30
    • 1970-01-01
    • 2021-05-06
    • 1970-01-01
    • 1970-01-01
    • 2021-09-05
    相关资源
    最近更新 更多