Skip to content

Commit 668629d

Browse files
wickdynexdsyer
authored andcommitted
refactor OwnerRepository:
-<replace>: use `JpaRepository` to replace `Repository` in `OwnerRepository` class. -<remove1>: remove `save()` method. JpaRepository provides it by default. -<remove2>: remove `@Query` because in `Owner` class, the `@OneToMany` annotiation achieved `fetch` in query. -<refactor1>: use `Optional<Owner>` to recieve the result from `findById()`, and if is null, throw `IllegalArugmentExpection`. -<refactor2>: achieve the assert to judge return value in tests. -<add>: add name to `@author` tag.
1 parent a3026bd commit 668629d

File tree

11 files changed

+85
-32
lines changed

11 files changed

+85
-32
lines changed

src/main/java/org/springframework/samples/petclinic/model/NamedEntity.java

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525
*
2626
* @author Ken Krebs
2727
* @author Juergen Hoeller
28+
* @author Wick Dynex
2829
*/
2930
@MappedSuperclass
3031
public class NamedEntity extends BaseEntity {

src/main/java/org/springframework/samples/petclinic/owner/Owner.java

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@
4141
* @author Sam Brannen
4242
* @author Michael Isvy
4343
* @author Oliver Drotbohm
44+
* @author Wick Dynex
4445
*/
4546
@Entity
4647
@Table(name = "owners")

src/main/java/org/springframework/samples/petclinic/owner/OwnerController.java

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
package org.springframework.samples.petclinic.owner;
1717

1818
import java.util.List;
19+
import java.util.Optional;
1920

2021
import org.springframework.data.domain.Page;
2122
import org.springframework.data.domain.PageRequest;
@@ -40,6 +41,7 @@
4041
* @author Ken Krebs
4142
* @author Arjen Poutsma
4243
* @author Michael Isvy
44+
* @author Wick Dynex
4345
*/
4446
@Controller
4547
class OwnerController {
@@ -59,7 +61,10 @@ public void setAllowedFields(WebDataBinder dataBinder) {
5961

6062
@ModelAttribute("owner")
6163
public Owner findOwner(@PathVariable(name = "ownerId", required = false) Integer ownerId) {
62-
return ownerId == null ? new Owner() : this.owners.findById(ownerId);
64+
return ownerId == null ? new Owner()
65+
: this.owners.findById(ownerId)
66+
.orElseThrow(() -> new IllegalArgumentException("Owner not found with id: " + ownerId
67+
+ ". Please ensure the ID is correct " + "and the owner exists in the database."));
6368
}
6469

6570
@GetMapping("/owners/new")
@@ -158,7 +163,9 @@ public String processUpdateOwnerForm(@Valid Owner owner, BindingResult result, @
158163
@GetMapping("/owners/{ownerId}")
159164
public ModelAndView showOwner(@PathVariable("ownerId") int ownerId) {
160165
ModelAndView mav = new ModelAndView("owners/ownerDetails");
161-
Owner owner = this.owners.findById(ownerId);
166+
Optional<Owner> optionalOwner = this.owners.findById(ownerId);
167+
Owner owner = optionalOwner.orElseThrow(() -> new IllegalArgumentException(
168+
"Owner not found with id: " + ownerId + ". Please ensure the ID is correct "));
162169
mav.addObject(owner);
163170
return mav;
164171
}

src/main/java/org/springframework/samples/petclinic/owner/OwnerRepository.java

Lines changed: 17 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -16,12 +16,16 @@
1616
package org.springframework.samples.petclinic.owner;
1717

1818
import java.util.List;
19+
import java.util.Optional;
1920

21+
import jakarta.annotation.Nonnull;
22+
import jakarta.validation.constraints.NotNull;
2023
import org.springframework.data.domain.Page;
2124
import org.springframework.data.domain.Pageable;
25+
import org.springframework.data.jpa.repository.JpaRepository;
2226
import org.springframework.data.jpa.repository.Query;
23-
import org.springframework.data.repository.Repository;
2427
import org.springframework.data.repository.query.Param;
28+
import org.springframework.lang.NonNullApi;
2529
import org.springframework.transaction.annotation.Transactional;
2630

2731
/**
@@ -34,8 +38,9 @@
3438
* @author Juergen Hoeller
3539
* @author Sam Brannen
3640
* @author Michael Isvy
41+
* @author Wick Dynex
3742
*/
38-
public interface OwnerRepository extends Repository<Owner, Integer> {
43+
public interface OwnerRepository extends JpaRepository<Owner, Integer> {
3944

4045
/**
4146
* Retrieve all {@link PetType}s from the data store.
@@ -52,25 +57,24 @@ public interface OwnerRepository extends Repository<Owner, Integer> {
5257
* @return a Collection of matching {@link Owner}s (or an empty Collection if none
5358
* found)
5459
*/
55-
5660
@Query("SELECT DISTINCT owner FROM Owner owner left join owner.pets WHERE owner.lastName LIKE :lastName% ")
5761
@Transactional(readOnly = true)
5862
Page<Owner> findByLastName(@Param("lastName") String lastName, Pageable pageable);
5963

6064
/**
6165
* Retrieve an {@link Owner} from the data store by id.
66+
* <p>
67+
* This method returns an {@link Optional} containing the {@link Owner} if found. If
68+
* no {@link Owner} is found with the provided id, it will return an empty
69+
* {@link Optional}.
70+
* </p>
6271
* @param id the id to search for
63-
* @return the {@link Owner} if found
64-
*/
65-
@Query("SELECT owner FROM Owner owner left join fetch owner.pets WHERE owner.id =:id")
66-
@Transactional(readOnly = true)
67-
Owner findById(@Param("id") Integer id);
68-
69-
/**
70-
* Save an {@link Owner} to the data store, either inserting or updating it.
71-
* @param owner the {@link Owner} to save
72+
* @return an {@link Optional} containing the {@link Owner} if found, or an empty
73+
* {@link Optional} if not found.
74+
* @throws IllegalArgumentException if the id is null (assuming null is not a valid
75+
* input for id)
7276
*/
73-
void save(Owner owner);
77+
Optional<Owner> findById(@Nonnull Integer id);
7478

7579
/**
7680
* Returns all the owners from data store

src/main/java/org/springframework/samples/petclinic/owner/Pet.java

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@
3939
* @author Ken Krebs
4040
* @author Juergen Hoeller
4141
* @author Sam Brannen
42+
* @author Wick Dynex
4243
*/
4344
@Entity
4445
@Table(name = "pets")

src/main/java/org/springframework/samples/petclinic/owner/PetController.java

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717

1818
import java.time.LocalDate;
1919
import java.util.Collection;
20+
import java.util.Optional;
2021

2122
import org.springframework.stereotype.Controller;
2223
import org.springframework.ui.ModelMap;
@@ -37,6 +38,7 @@
3738
* @author Juergen Hoeller
3839
* @author Ken Krebs
3940
* @author Arjen Poutsma
41+
* @author Wick Dynex
4042
*/
4143
@Controller
4244
@RequestMapping("/owners/{ownerId}")
@@ -57,8 +59,9 @@ public Collection<PetType> populatePetTypes() {
5759

5860
@ModelAttribute("owner")
5961
public Owner findOwner(@PathVariable("ownerId") int ownerId) {
60-
61-
Owner owner = this.owners.findById(ownerId);
62+
Optional<Owner> optionalOwner = this.owners.findById(ownerId);
63+
Owner owner = optionalOwner.orElseThrow(() -> new IllegalArgumentException(
64+
"Owner not found with id: " + ownerId + ". Please ensure the ID is correct "));
6265
if (owner == null) {
6366
throw new IllegalArgumentException("Owner ID not found: " + ownerId);
6467
}
@@ -73,7 +76,9 @@ public Pet findPet(@PathVariable("ownerId") int ownerId,
7376
return new Pet();
7477
}
7578

76-
Owner owner = this.owners.findById(ownerId);
79+
Optional<Owner> optionalOwner = this.owners.findById(ownerId);
80+
Owner owner = optionalOwner.orElseThrow(() -> new IllegalArgumentException(
81+
"Owner not found with id: " + ownerId + ". Please ensure the ID is correct "));
7782
if (owner == null) {
7883
throw new IllegalArgumentException("Owner ID not found: " + ownerId);
7984
}

src/main/java/org/springframework/samples/petclinic/owner/VisitController.java

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,8 @@
1616
package org.springframework.samples.petclinic.owner;
1717

1818
import java.util.Map;
19+
import java.util.Optional;
20+
import java.util.OptionalInt;
1921

2022
import org.springframework.stereotype.Controller;
2123
import org.springframework.validation.BindingResult;
@@ -35,6 +37,7 @@
3537
* @author Arjen Poutsma
3638
* @author Michael Isvy
3739
* @author Dave Syer
40+
* @author Wick Dynex
3841
*/
3942
@Controller
4043
class VisitController {
@@ -60,7 +63,9 @@ public void setAllowedFields(WebDataBinder dataBinder) {
6063
@ModelAttribute("visit")
6164
public Visit loadPetWithVisit(@PathVariable("ownerId") int ownerId, @PathVariable("petId") int petId,
6265
Map<String, Object> model) {
63-
Owner owner = this.owners.findById(ownerId);
66+
Optional<Owner> optionalOwner = owners.findById(ownerId);
67+
Owner owner = optionalOwner.orElseThrow(() -> new IllegalArgumentException(
68+
"Owner not found with id: " + ownerId + ". Please ensure the ID is correct "));
6469

6570
Pet pet = owner.getPet(petId);
6671
model.put("pet", pet);

src/test/java/org/springframework/samples/petclinic/owner/OwnerControllerTests.java

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@
3131
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
3232

3333
import java.time.LocalDate;
34+
import java.util.Optional;
3435

3536
import static org.hamcrest.Matchers.empty;
3637
import static org.hamcrest.Matchers.greaterThan;
@@ -52,6 +53,7 @@
5253
* Test class for {@link OwnerController}
5354
*
5455
* @author Colin But
56+
* @author Wick Dynex
5557
*/
5658
@WebMvcTest(OwnerController.class)
5759
@DisabledInNativeImage
@@ -94,7 +96,7 @@ void setup() {
9496

9597
given(this.owners.findAll(any(Pageable.class))).willReturn(new PageImpl<>(Lists.newArrayList(george)));
9698

97-
given(this.owners.findById(TEST_OWNER_ID)).willReturn(george);
99+
given(this.owners.findById(TEST_OWNER_ID)).willReturn(Optional.of(george));
98100
Visit visit = new Visit();
99101
visit.setDate(LocalDate.now());
100102
george.getPet("Max").getVisits().add(visit);
@@ -240,7 +242,7 @@ public void testProcessUpdateOwnerFormWithIdMismatch() throws Exception {
240242
owner.setCity("New York");
241243
owner.setTelephone("0123456789");
242244

243-
when(owners.findById(pathOwnerId)).thenReturn(owner);
245+
when(owners.findById(pathOwnerId)).thenReturn(Optional.of(owner));
244246

245247
mockMvc.perform(MockMvcRequestBuilders.post("/owners/{ownerId}/edit", pathOwnerId).flashAttr("owner", owner))
246248
.andExpect(status().is3xxRedirection())

src/test/java/org/springframework/samples/petclinic/owner/PetControllerTests.java

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@
4646
* Test class for the {@link PetController}
4747
*
4848
* @author Colin But
49+
* @author Wick Dynex
4950
*/
5051
@WebMvcTest(value = PetController.class,
5152
includeFilters = @ComponentScan.Filter(value = PetTypeFormatter.class, type = FilterType.ASSIGNABLE_TYPE))
@@ -79,7 +80,7 @@ void setup() {
7980
dog.setId(TEST_PET_ID + 1);
8081
pet.setName("petty");
8182
dog.setName("doggy");
82-
given(this.owners.findById(TEST_OWNER_ID)).willReturn(owner);
83+
given(this.owners.findById(TEST_OWNER_ID)).willReturn(Optional.of(owner));
8384
}
8485

8586
@Test

src/test/java/org/springframework/samples/petclinic/owner/VisitControllerTests.java

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,10 +32,13 @@
3232
import org.springframework.test.context.aot.DisabledInAotMode;
3333
import org.springframework.test.web.servlet.MockMvc;
3434

35+
import java.util.Optional;
36+
3537
/**
3638
* Test class for {@link VisitController}
3739
*
3840
* @author Colin But
41+
* @author Wick Dynex
3942
*/
4043
@WebMvcTest(VisitController.class)
4144
@DisabledInNativeImage
@@ -58,7 +61,7 @@ void init() {
5861
Pet pet = new Pet();
5962
owner.addPet(pet);
6063
pet.setId(TEST_PET_ID);
61-
given(this.owners.findById(TEST_OWNER_ID)).willReturn(owner);
64+
given(this.owners.findById(TEST_OWNER_ID)).willReturn(Optional.of(owner));
6265
}
6366

6467
@Test

0 commit comments

Comments
 (0)