JPA EntityGraph DISTINCT with Parameter 结果为笛卡尔积



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 个报告消息但是,当我向查询添加参数表时,我得到了笛卡尔乘积:

@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 条报告消息,但得到 84 条。使用命名查询,我得到相同的结果。这是怎么回事?

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

最新更新