060. Performance Tuning - dkkahm/study-spring-jpa GitHub Wiki

Statistics Log

spring.jpa.properties.hibernate.generate_statistics=true
logging.level.org.hibernate.stat=debug

Indexes

  • Look at Execution Plan

Avoid N+1 problem

  • N+1 problem
    List<Course> courses = em
            .createNamedQuery("query_get_all_courses", Course.class)
            .getResultList();
    for(Course course : courses) {
        logger.info("Course: {}, Students: {}", course, course.getStudents());  // Second Fetching Occurs !!!!!
    }
  • Make Course.students eager is not a solution
  • EntityGraph
        EntityGraph<Course> entityGraph = em.createEntityGraph(Course.class);
        Subgraph<Object> subGraph = entityGraph.addSubgraph("students");

        List<Course> courses = em
                .createQuery("Select c From Course c", Course.class)
                .setHint("javax.persistence.loadgraph", entityGraph)
                .getResultList();
        for(Course course : courses) {
            logger.info("Course: {}, Students: {}", course, course.getStudents());
        }
  • JOIN FETCH
        List<Course> courses = em
                .createQuery("Select c From Course c JOIN FETCH c.students", Course.class)
                .getResultList();
        for(Course course : courses) {
            logger.info("Course: {}, Students: {}", course, course.getStudents());
        }
⚠️ **GitHub.com Fallback** ⚠️