0

2 I have an entity with 4 1:n relationships

@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;

I want to use the entity graph for eager fetching

@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;
}

this method works like expected: I have 8 entries in the DB and it return 8 ReportMessage However when I add a paremeter to the query I get back the cartesian product:

@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;
    }

I expect to get back 1 ReportMessage but get 84. With a named query I get the same result. What’s going on?

Hans
  • 145
  • 9
  • How about you look at the SQL invoked and give your opinion based on that evidence? –  Jan 28 '19 at 14:58

1 Answers1

0

The problem was caused by the bidirectional relations. After changing to unidirectional relations the code works like expected. However, does anybody know if I have a bug in my original code, or if this is a hibernate or not specified in JPA?

Hans
  • 145
  • 9