Skip to content

Commit

Permalink
Closes #28 - Refactored CategoryRepository findByName method
Browse files Browse the repository at this point in the history
  • Loading branch information
kschafer2 committed Aug 31, 2019
1 parent a11ab37 commit 24e08f1
Show file tree
Hide file tree
Showing 4 changed files with 12 additions and 9 deletions.
8 changes: 2 additions & 6 deletions src/main/java/guru/springframework/bootstrap/Bootstrap.java
Original file line number Diff line number Diff line change
Expand Up @@ -44,9 +44,7 @@ private void loadCategories() {
new Category("Nuts")
);

for(Category category : categories) {
categoryRepository.save(category);
}
categories.forEach(categoryRepository::save);

System.out.println("Loaded Category Count: " + categoryRepository.count());
}
Expand All @@ -60,9 +58,7 @@ private void loadCustomers() {
new Customer("Mickey", "Mouse")
);

for(Customer customer : customers) {
customerRepository.save(customer);
}
customers.forEach(customerRepository::save);

System.out.println("Loaded Customer Count: " + customerRepository.count());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@
import guru.springframework.domain.Category;
import org.springframework.data.jpa.repository.JpaRepository;

import java.util.Optional;

public interface CategoryRepository extends JpaRepository<Category, Long> {

Category findByName(String name);
Optional<Category> findByName(String name);
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import guru.springframework.api.v1.mappers.CategoryMapper;
import guru.springframework.api.v1.model.CategoryDto;
import guru.springframework.exceptions.ResourceNotFoundException;
import guru.springframework.repositories.CategoryRepository;
import org.springframework.stereotype.Service;

Expand Down Expand Up @@ -31,6 +32,9 @@ public List<CategoryDto> getAllCategories() {

@Override
public CategoryDto getCategoryByName(String name) {
return categoryMapper.toDto(categoryRepository.findByName(name));
return categoryRepository
.findByName(name)
.map(categoryMapper::toDto)
.orElseThrow(ResourceNotFoundException::new);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

import java.util.Arrays;
import java.util.List;
import java.util.Optional;

import static org.junit.Assert.assertEquals;
import static org.mockito.ArgumentMatchers.anyString;
Expand Down Expand Up @@ -54,7 +55,7 @@ public void getCategoryByName() throws Exception {
//given
Category category = new Category(ID, NAME);

when(categoryRepository.findByName(anyString())).thenReturn(category);
when(categoryRepository.findByName(anyString())).thenReturn(Optional.of(category));

//when
CategoryDto categoryDTO = categoryService.getCategoryByName(NAME);
Expand Down

0 comments on commit 24e08f1

Please sign in to comment.