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

前端 未结 5 875
萌比男神i
萌比男神i 2020-12-29 08:07

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 brev         


        
5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-29 09:00

    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).

提交回复
热议问题