17

I have the following two annotated classes that I use to build a graph:

@Entity
@Table(name = "Edge")
public class Edge
{
    /* some code omitted for brevity */

    @ManyToOne
    @JoinColumn(name = "ixNodeFrom", nullable = false)
    private Node         _nodFrom;

    @ManyToOne
    @JoinColumn(name = "ixNodeTo", nullable = false)
    private Node         _nodTo;

    /* some code omitted for brevity */
}

@Entity
@Table(name = "Node")
public class Node
{
    /* some code omitted for brevity */

    @OneToMany(mappedBy = "_nodTo")
    private Set<Edge>    _rgInbound;

    @OneToMany(mappedBy = "_nodFrom")
    private Set<Edge>    _rgOutbound;

    /* some code omitted for brevity */
}

Now, when I build the graph, I issue two queries to fetch all rows from either table and set up the child / parent references, for which I need the ids stored in the Edge table.

Because I have defined the relation between the two tables in JPA, accessing the edge object to get the two nodes' ids triggers two SQL statements per edge, when the JPA provider lazily * loads the associated nodes. Since I already have the node objects, and the ids have already been loaded from the edge table, I want to skip those queries, as they take an awfully long time for larger graphs.

I tried adding these lines to the Edge class, but then my JPA provider wants me to make one mapping read-only, and I can't seem to find a way how to do that:

@Column(name = "ixNodeTo")
private long _ixNodeTo;

@Column(name = "ixNodeFrom")
private long _ixNodeFrom;

I'm using Eclipselink and MySQL, if it matters.


**The default behaviour for @ManyToOne actually is eager loading, see Pascal's answer*

Community
  • 1
  • 1
Hanno Fietz
  • 30,799
  • 47
  • 148
  • 234

5 Answers5

17

I got three good answers that were equally helpful, and by now none percolated to the top by public vote, so I'm merging them together here for a single comprehensive answer:

a) Change the query

You can load the whole graph at once by changing the query, thereby giving the JPA provider a chance to realize that it already has everything in memory and doesn't need to go back to the DB:

List<Node> nodes = em.createQuery(
        "SELECT DISTINCT n FROM Node n LEFT JOIN FETCH n._rgOutbound")
        .getResultList();

(via axtavt)

b) Use read-only fields for the FKs

Loading the FKs into their own fields, as described in the question, will also work if, as the JPA provider is demanding, the fields are declared to be readonly, which is done like this:

@Column(name = "ixNodeTo", insertable = false, updatable = false)

(via bravocharlie)

c) Use property access

If you are using property access instead of field access, the JPA provider also gets a chance to realize it already has the FK and doesn't need to fetch the referenced object. In short, property access means that you put the JPA annotations on the getter, thereby "promising" the JPA provider that your getter won't go and access the rest of the object. More details in this question. This will work for Hibernate, and for Eclipselink, it will work (assumed in the original answer, experimentally confirmed by me) with weaving enabled. (via Pascal Thivent)


Additionally, as Pascal points out in his answer, @ManyToOne, contrary to my original post, is not lazy-loading, but eager-loading by default, and changing that will require weaving as well.

Community
  • 1
  • 1
Hanno Fietz
  • 30,799
  • 47
  • 148
  • 234
  • 1
    A limitation regarding (c) you have to be in a transaction. – Mike Argyriou Feb 08 '16 at 12:02
  • Hello, sorry to dig this one out. Could you provide the example for c)? Because I tried it and it still triggered the extra query. I am using ELink 2.7.4 with Payara so I am assuming weaving is enabled. I edited the field to @Transient and used @Access(AccessType.PROPERTY on the getter with it grabbing the entity2.getIId(). Option b) did it for me, but I am interested in finding out if c) is really viable, or if I am just missing something. – CarlosGoncalves Apr 20 '21 at 17:31
  • 1
    @CarlosGoncalves, sorry, I don't have an example handy, and I'm not even sure whether this is still valid anymore, it is already quite an old answer. – Hanno Fietz Apr 29 '21 at 10:48
13

Have you tried

@Column(name = "ixNodeTo", insertable = false, updatable = false)
bravocharlie
  • 321
  • 1
  • 3
4

How can I retrieve the foreign key from a JPA ManyToOne mapping without hitting the target table?

In theory, a JPA provider should be able to not trigger a query when calling

someEdge.getNodeFrom().getId()

as it already has the id (as FK).

I'm 100% sure Hibernate can (assuming you're using property access). In the case of EclipseLink, I don't know (if it does, it will probably requires weaving).

Because I have defined the relation between the two tables in JPA, accessing the edge object to get the two nodes' ids triggers two SQL statements per edge, when the JPA provider lazily loads the associated nodes. Since I already have the node objects, and the ids have already been loaded from the edge table, I want to skip those queries, as they take an awfully long time for larger graphs.

Note that @ManyToOne uses an EAGER strategy by default. If you want to make it LAZY, you have to decalre it explicitly (but again, this will require weaving of your classes with EclipseLink).

Community
  • 1
  • 1
Pascal Thivent
  • 562,542
  • 136
  • 1,062
  • 1,124
  • Thanks for all the hints, this should help me fix this. I'm going to look at the property access thing, I'm using field access at the minute. – Hanno Fietz Oct 18 '10 at 07:02
2

I think you should try to optimize your query rather than change the mapping. For example, the following query fetches the whole graph at once (tested in Hibernate):

List<Node> nodes = em.createQuery(
            "SELECT DISTINCT n FROM Node n LEFT JOIN FETCH n._rgOutbound")
            .getResultList();
axtavt
  • 239,438
  • 41
  • 511
  • 482
0

How about using getReference()?

For example:

Node fkNode = em.getReference(edge.getNodeFrom()); // [1]
fkNode.getId()

[1] This will not trigger a SQL query to retrieve the nodeFrom

Mike Argyriou
  • 1,250
  • 2
  • 18
  • 30