Fix lazy loading issue in owner details

This commit is contained in:
Dave Syer 2022-01-10 08:08:43 +00:00
parent 8a28801d1a
commit e765e3ffe1
3 changed files with 26 additions and 3 deletions

View file

@ -18,6 +18,7 @@ package org.springframework.samples.petclinic.owner;
import java.util.List;
import java.util.Map;
import javax.transaction.Transactional;
import javax.validation.Valid;
import org.springframework.data.domain.Page;
@ -153,11 +154,12 @@ class OwnerController {
* @return a ModelMap with the model attributes for the view
*/
@GetMapping("/owners/{ownerId}")
@Transactional
public ModelAndView showOwner(@PathVariable("ownerId") int ownerId) {
ModelAndView mav = new ModelAndView("owners/ownerDetails");
Owner owner = this.owners.findById(ownerId);
for (Pet pet : owner.getPets()) {
pet.getVisits();
pet.getVisits().size();
}
mav.addObject(owner);
return mav;

View file

@ -16,21 +16,43 @@
package org.springframework.samples.petclinic;
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.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.http.HttpStatus;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.samples.petclinic.vet.VetRepository;
import org.springframework.web.client.RestTemplate;
@SpringBootTest
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
class PetclinicIntegrationTests {
@LocalServerPort
int port;
@Autowired
private VetRepository vets;
@Autowired
private RestTemplateBuilder builder;
@Test
void testFindAll() throws Exception {
vets.findAll();
vets.findAll(); // served from cache
}
@Test
void testOwnerDetails() {
RestTemplate template = builder.rootUri("http://localhost:" + port).build();
ResponseEntity<String> result = template.exchange(RequestEntity.get("/owners/1").build(), String.class);
assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK);
}
}

View file

@ -31,7 +31,6 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;
import java.time.LocalDate;
import java.util.Collections;
import java.util.List;
import org.assertj.core.util.Lists;