This guide explains how to use
JPA Entity Graph in
Spring Boot with H2 to optimize queries and avoid unnecessary lazy loading.
1. Add Dependencies
In
pom.xml:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
2. Configure H2
In
application.properties:
spring.datasource.url=jdbc:h2:mem:entitydb
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.hibernate.ddl-auto=create
spring.h2.console.enabled=true
3. Define Entities
Employee and
Department:
@Entity
public class Department {
@Id @GeneratedValue
private Long id;
private String name;
}
@Entity
public class Employee {
@Id @GeneratedValue
private Long id;
private String name;
@ManyToOne(fetch = FetchType.LAZY)
private Department department;
}
4. Repository with Entity Graph
public interface EmployeeRepository extends JpaRepository<Employee, Long> {
@EntityGraph(attributePaths = "department")
List<Employee> findAll();
}
Here, the
department is eagerly fetched using an entity graph.
5. Test Query
@SpringBootTest
class EmployeeRepoTest {
@Autowired EmployeeRepository repo;
@Test
void testFindAllWithGraph() {
repo.findAll().forEach(e -> System.out.println(e.getDepartment().getName()));
}
}
No lazy initialization exception will occur since
department is fetched eagerly.
image quote pre code