Named Entity Graph Sub-Subgraph

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()));
                });
        });
    }

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.

Tags:

Java

Jpa 2.1