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个。使用命名查询,我得到相同的结果。发生了什么事?
答案 0 :(得分:0)
该问题是由双向关系引起的。更改为单向关系后,代码将按预期工作。 但是,有人知道我的原始代码中是否有错误,或者这是休眠状态,还是未在JPA中指定?