35

I am new to JPA 2.1 and started using only recently Named Entity Graphs. For my project I am mapping the following relation in JPA 2.1:

Order -> OrderDetail -> Product -> ProductLine

The question:

I want to instruct JPA to join and fetch properly all the needed data. So far this works flawlessly for Order -> OrderDetail -> Product but I have not managed so far to add a Sub-Sub Graph in order to go as deep as the ProductLine class. How do I make a subgraph of a subgraph ? Ex get the ProductLine of the Product ?

Here are my entities (getters and setters omitted):

Order

@Entity
@Table(name="ORDERS")
@NamedEntityGraph(
    name = "graph.Order.details",
    attributeNodes = {
        @NamedAttributeNode(value = "details", subgraph = "graph.OrderDetail.product")
    },
    subgraphs = {
        @NamedSubgraph(name = "graph.OrderDetail.product", attributeNodes = @NamedAttributeNode("product"))
    }
)

public class Order implements Serializable{
  @Id
  @Column(name = "orderNumber")
  private Long number;

  @Column(name = "orderDate")
  private Date date;

  @OneToMany(mappedBy = "order")
  private List<OrderDetail> details;
}

OrderDetail

@Entity
@Table(name = "orderdetails")
public class OrderDetail implements Serializable{

   @ManyToOne(fetch = FetchType.LAZY)
   @JoinColumn(name = "orderNumber")
   @Id
   private Order order;

   @ManyToOne(fetch = FetchType.LAZY)
   @JoinColumn(name = "productCode", nullable = false)
   @Id
   private Product product;

   @Column(name = "orderLineNumber")
   private int lineNumber;

   @Column(name = "quantityOrdered")
   private int quantity;

Product

@Entity
@Table(name = "products")
class Product {
    @Column(name = "productCode")
    @Id
    private String code;

    @Column(name = "quantityInStock")
    public int quantity;

    @ManyToOne
    @JoinColumn(name = "productLine")
    private ProductLine line;

ProductLine

@Entity
@Table(name = "productlines")
public class ProductLine {
    @Id
    @Column(name = "productLine")
    private String line;

    @Column
    private String textDescription;
Community
  • 1
  • 1
sashok_bg
  • 2,436
  • 1
  • 22
  • 33
  • Not sure if that is even possible, but what happens if you create another NamedSubgraph under subgraphs, specify its type to be Product, with the attributenodes being line, and then reference that from the @NamedAttributeNode("product") you have? – Jan-Willem Gmelig Meyling Aug 16 '16 at 20:38
  • Check second answer: https://stackoverflow.com/a/54147717/316343 – Jahan Zinedine Aug 13 '21 at 13:22

3 Answers3

19

The simple answer is that you cannot do this because, with the current JPA implementation, you would end up doing two separate queries and having to deal with the Cartesian Products. Some future version of JPA could be extended to include more levels of subgraphs, but as it stands today it does not. There is a JPA SPEC group that works on the next version of JPA. Feel free to submit your request/suggestion there.

Here on StackOverflow there is another reference to the same question.

Apostolos
  • 10,033
  • 5
  • 24
  • 39
Daniel Wisehart
  • 1,489
  • 12
  • 31
6

You can create multi level entity graphs with dynamic entity graphs. I am using jpa 2.2 and Hibernate 5.3.7 and i am able to create entity graphs and fetch data upto 3 levels . I hope this will work for next level too . Below is the code snippet . For more details and actual code you can checkout my github repo : https://github.com/vaneetkataria/Jpa-Hibernate/blob/master/jdbcToJpaMigration/src/test/java/com/katariasoft/technologies/jpaHibernate/entity/fetch/entitygraph/dynamic/MultiInstructorsDynamicEntityGrpahTests.java

Code snippet :

@SuppressWarnings("unchecked")
    @Test
    @Rollback(false)
    public void fetchInstrctrsIdProofVehiclesStudentsTheirInstructorsVehiclesAndTheirDocuments() {
        doInTransaction(() -> {
            EntityGraph<Instructor> instructorGraph = em.createEntityGraph(Instructor.class);
            instructorGraph.addAttributeNodes(Instructor_.idProof, Instructor_.vehicles);
            Subgraph<Student> studentSubgraph = instructorGraph.addSubgraph(Instructor_.STUDENTS);
            studentSubgraph.addAttributeNodes(Student_.instructors);
            Subgraph<Vehicle> vehicleSubgraph = studentSubgraph.addSubgraph(Student_.VEHICLES);
            vehicleSubgraph.addAttributeNodes(Vehicle_.documents);
            TypedQuery<Instructor> query = em.createQuery("select i from Instructor i ", Instructor.class)
                    .setHint(EntityGraphUtils.FETCH_GRAPH, instructorGraph);
            List<Instructor> instructors = query.getResultList();
            if (Objects.nonNull(instructors))
                instructors.forEach(instructor -> {
                    IdProof idProof = instructor.getIdProof();
                    Set<Vehicle> vehicles = instructor.getVehicles();
                    Set<Student> students = instructor.getStudents();
                    System.out.println(instructor);
                    System.out.println(idProof);
                    if (Objects.nonNull(vehicles))
                        vehicles.forEach(v -> System.out.println(v.getVehicleNumber()));
                    if (Objects.nonNull(students))
                        students.forEach(s -> System.out.println(s.getName()));
                });
        });
    }
Vaneet Kataria
  • 575
  • 5
  • 14
0

Every NamedAttributeNode can specify a subgraph.

@Entity
@Table(name="ORDERS")
@NamedEntityGraph(
    name = "graph.Order.details",
    attributeNodes = {
        @NamedAttributeNode(value = "details", subgraph = "graph.OrderDetail.product")
    },
    subgraphs = {
        @NamedSubgraph(name = "graph.OrderDetail.product", attributeNodes = @NamedAttributeNode(value = "product", subgraph = "graph.Product.productLine")),
        @NamedSubgraph(name = "graph.Product.productLine", attributeNodes = @NamedAttributeNode("line"))
    }
)
Apostolos
  • 10,033
  • 5
  • 24
  • 39
  • 1
    Sorry. Not sure it was possible three years ago, but definitely is now. I use one that joins the same table from two different entity paths (one is one subgraph deep, the other is three subgraphs deep) and then performs an additional join on both with another subgraph. – BWarren Apr 22 '22 at 19:29