0

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 个。使用命名查询我得到相同的结果。这是怎么回事?

4

1 回答 1

0

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

于 2019-01-29T11:09:22.513 回答