mirror of
https://github.com/spring-projects/spring-petclinic.git
synced 2026-02-05 05:41:11 +00:00
Use LAZY fetch for owner pets and load associations explicitly with EntityGraph
Signed-off-by: Ravindra Bijarniya <ravindrabijarniya123@gmail.com>
This commit is contained in:
parent
ab1d5364a0
commit
50dcd425e3
3 changed files with 36 additions and 1 deletions
|
|
@ -61,7 +61,7 @@ public class Owner extends Person {
|
|||
@Pattern(regexp = "\\d{10}", message = "{telephone.invalid}")
|
||||
private String telephone;
|
||||
|
||||
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
|
||||
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
|
||||
@JoinColumn(name = "owner_id")
|
||||
@OrderBy("name")
|
||||
private final List<Pet> pets = new ArrayList<>();
|
||||
|
|
|
|||
|
|
@ -19,6 +19,7 @@ import java.util.Optional;
|
|||
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.jpa.repository.EntityGraph;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
/**
|
||||
|
|
@ -42,6 +43,7 @@ public interface OwnerRepository extends JpaRepository<Owner, Integer> {
|
|||
* @return a Collection of matching {@link Owner}s (or an empty Collection if none
|
||||
* found)
|
||||
*/
|
||||
@EntityGraph(attributePaths = {"pets", "pets.type"})
|
||||
Page<Owner> findByLastNameStartingWith(String lastName, Pageable pageable);
|
||||
|
||||
/**
|
||||
|
|
@ -57,6 +59,9 @@ public interface OwnerRepository extends JpaRepository<Owner, Integer> {
|
|||
* @throws IllegalArgumentException if the id is null (assuming null is not a valid
|
||||
* input for id)
|
||||
*/
|
||||
@Override
|
||||
@EntityGraph(attributePaths = {"pets", "pets.type", "pets.visits"})
|
||||
Optional<Owner> findById(Integer id);
|
||||
|
||||
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,30 @@
|
|||
package org.springframework.samples.petclinic.owner;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
@SpringBootTest
|
||||
@Transactional
|
||||
class OwnerRepositoryTests {
|
||||
|
||||
@Autowired
|
||||
private OwnerRepository ownerRepository;
|
||||
|
||||
@Test
|
||||
void shouldFetchOwnersWithPetsUsingEntityGraph() {
|
||||
Page<Owner> owners =
|
||||
ownerRepository.findByLastNameStartingWith("D", PageRequest.of(0, 10));
|
||||
|
||||
assertThat(owners).isNotEmpty();
|
||||
|
||||
Owner owner = owners.getContent().get(0);
|
||||
|
||||
assertThat(owner.getPets()).isNotNull();
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue