This commit is contained in:
Ravindra Bijarniya 2026-01-12 11:07:20 +00:00 committed by GitHub
commit bad75e950b
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 36 additions and 1 deletions

View file

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

View file

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

View file

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