Skip to content

Commit

Permalink
Refactor code logic
Browse files Browse the repository at this point in the history
<refactor>: remove useless logic cod.
<refactor>: detele useless annotation which is provided by Jpa.
<refactor>: refactor implement of `findByLastName`, use Jpa to simplify query.
  • Loading branch information
wickdynex committed Nov 11, 2024
1 parent 668629d commit b597839
Show file tree
Hide file tree
Showing 5 changed files with 11 additions and 24 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ private String addPaginationModel(int page, Model model, Page<Owner> paginated)
private Page<Owner> findPaginatedForOwnersLastName(int page, String lastname) {
int pageSize = 5;
Pageable pageable = PageRequest.of(page - 1, pageSize);
return owners.findByLastName(lastname, pageable);
return owners.findByLastNameStartingWith(lastname, pageable);
}

@GetMapping("/owners/{ownerId}/edit")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,11 @@
import java.util.Optional;

import jakarta.annotation.Nonnull;
import jakarta.validation.constraints.NotNull;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.lang.NonNullApi;
import org.springframework.transaction.annotation.Transactional;

/**
Expand Down Expand Up @@ -57,9 +55,7 @@ public interface OwnerRepository extends JpaRepository<Owner, Integer> {
* @return a Collection of matching {@link Owner}s (or an empty Collection if none
* found)
*/
@Query("SELECT DISTINCT owner FROM Owner owner left join owner.pets WHERE owner.lastName LIKE :lastName% ")
@Transactional(readOnly = true)
Page<Owner> findByLastName(@Param("lastName") String lastName, Pageable pageable);
Page<Owner> findByLastNameStartingWith(String lastName, Pageable pageable);

/**
* Retrieve an {@link Owner} from the data store by id.
Expand All @@ -79,8 +75,6 @@ public interface OwnerRepository extends JpaRepository<Owner, Integer> {
/**
* Returns all the owners from data store
**/
@Query("SELECT owner FROM Owner owner")
@Transactional(readOnly = true)
Page<Owner> findAll(Pageable pageable);

}
Original file line number Diff line number Diff line change
Expand Up @@ -62,9 +62,6 @@ public Owner findOwner(@PathVariable("ownerId") int ownerId) {
Optional<Owner> optionalOwner = this.owners.findById(ownerId);
Owner owner = optionalOwner.orElseThrow(() -> new IllegalArgumentException(
"Owner not found with id: " + ownerId + ". Please ensure the ID is correct "));
if (owner == null) {
throw new IllegalArgumentException("Owner ID not found: " + ownerId);
}
return owner;
}

Expand All @@ -79,9 +76,6 @@ public Pet findPet(@PathVariable("ownerId") int ownerId,
Optional<Owner> optionalOwner = this.owners.findById(ownerId);
Owner owner = optionalOwner.orElseThrow(() -> new IllegalArgumentException(
"Owner not found with id: " + ownerId + ". Please ensure the ID is correct "));
if (owner == null) {
throw new IllegalArgumentException("Owner ID not found: " + ownerId);
}
return owner.getPet(petId);
}

Expand All @@ -99,7 +93,6 @@ public void initPetBinder(WebDataBinder dataBinder) {
public String initCreationForm(Owner owner, ModelMap model) {
Pet pet = new Pet();
owner.addPet(pet);
model.put("pet", pet);
return VIEWS_PETS_CREATE_OR_UPDATE_FORM;
}

Expand All @@ -126,7 +119,7 @@ public String processCreationForm(Owner owner, @Valid Pet pet, BindingResult res
}

@GetMapping("/pets/{petId}/edit")
public String initUpdateForm(Owner owner, @PathVariable("petId") int petId, RedirectAttributes redirectAttributes) {
public String initUpdateForm() {
return VIEWS_PETS_CREATE_OR_UPDATE_FORM;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ private Owner george() {
void setup() {

Owner george = george();
given(this.owners.findByLastName(eq("Franklin"), any(Pageable.class)))
given(this.owners.findByLastNameStartingWith(eq("Franklin"), any(Pageable.class)))
.willReturn(new PageImpl<>(Lists.newArrayList(george)));

given(this.owners.findAll(any(Pageable.class))).willReturn(new PageImpl<>(Lists.newArrayList(george)));
Expand Down Expand Up @@ -144,14 +144,14 @@ void testInitFindForm() throws Exception {
@Test
void testProcessFindFormSuccess() throws Exception {
Page<Owner> tasks = new PageImpl<>(Lists.newArrayList(george(), new Owner()));
when(this.owners.findByLastName(anyString(), any(Pageable.class))).thenReturn(tasks);
when(this.owners.findByLastNameStartingWith(anyString(), any(Pageable.class))).thenReturn(tasks);
mockMvc.perform(get("/owners?page=1")).andExpect(status().isOk()).andExpect(view().name("owners/ownersList"));
}

@Test
void testProcessFindFormByLastName() throws Exception {
Page<Owner> tasks = new PageImpl<>(Lists.newArrayList(george()));
when(this.owners.findByLastName(eq("Franklin"), any(Pageable.class))).thenReturn(tasks);
when(this.owners.findByLastNameStartingWith(eq("Franklin"), any(Pageable.class))).thenReturn(tasks);
mockMvc.perform(get("/owners?page=1").param("lastName", "Franklin"))
.andExpect(status().is3xxRedirection())
.andExpect(view().name("redirect:/owners/" + TEST_OWNER_ID));
Expand All @@ -160,7 +160,7 @@ void testProcessFindFormByLastName() throws Exception {
@Test
void testProcessFindFormNoOwnersFound() throws Exception {
Page<Owner> tasks = new PageImpl<>(Lists.newArrayList());
when(this.owners.findByLastName(eq("Unknown Surname"), any(Pageable.class))).thenReturn(tasks);
when(this.owners.findByLastNameStartingWith(eq("Unknown Surname"), any(Pageable.class))).thenReturn(tasks);
mockMvc.perform(get("/owners?page=1").param("lastName", "Unknown Surname"))
.andExpect(status().isOk())
.andExpect(model().attributeHasFieldErrors("owner", "lastName"))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -82,10 +82,10 @@ class ClinicServiceTests {

@Test
void shouldFindOwnersByLastName() {
Page<Owner> owners = this.owners.findByLastName("Davis", pageable);
Page<Owner> owners = this.owners.findByLastNameStartingWith("Davis", pageable);
assertThat(owners).hasSize(2);

owners = this.owners.findByLastName("Daviss", pageable);
owners = this.owners.findByLastNameStartingWith("Daviss", pageable);
assertThat(owners).isEmpty();
}

Expand All @@ -103,7 +103,7 @@ void shouldFindSingleOwnerWithPet() {
@Test
@Transactional
void shouldInsertOwner() {
Page<Owner> owners = this.owners.findByLastName("Schultz", pageable);
Page<Owner> owners = this.owners.findByLastNameStartingWith("Schultz", pageable);
int found = (int) owners.getTotalElements();

Owner owner = new Owner();
Expand All @@ -115,7 +115,7 @@ void shouldInsertOwner() {
this.owners.save(owner);
assertThat(owner.getId()).isNotZero();

owners = this.owners.findByLastName("Schultz", pageable);
owners = this.owners.findByLastNameStartingWith("Schultz", pageable);
assertThat(owners.getTotalElements()).isEqualTo(found + 1);
}

Expand Down

0 comments on commit b597839

Please sign in to comment.