Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 3c6288d

Browse files
add: Update Category REST API
1 parent 4dede2f commit 3c6288d

File tree

3 files changed

+24
-0
lines changed

3 files changed

+24
-0
lines changed

‎src/main/java/com/springboot/blog/controller/CategoryController.java‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,4 +38,13 @@ public ResponseEntity<CategoryDto> getCategory(@PathVariable("id") Long category
3838
public ResponseEntity<List<CategoryDto>> getCategories() {
3939
return ResponseEntity.ok(categoryService.getAllCategories());
4040
}
41+
42+
// build Update Category REST API
43+
@PreAuthorize("hasRole('ADMIN')")
44+
@PutMapping("{id}")
45+
public ResponseEntity<CategoryDto> updateCategory(
46+
@RequestBody CategoryDto categoryDto,
47+
@PathVariable("id") Long categoryId) {
48+
return ResponseEntity.ok(categoryService.updateCategory(categoryDto, categoryId));
49+
}
4150
}

‎src/main/java/com/springboot/blog/service/CategoryService.java‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,4 +11,6 @@ public interface CategoryService {
1111
CategoryDto getCategory(Long categoryId);
1212

1313
List<CategoryDto> getAllCategories();
14+
15+
CategoryDto updateCategory(CategoryDto categoryDto, Long categoryId);
1416
}

‎src/main/java/com/springboot/blog/service/impl/CategoryServiceImpl.java‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,4 +44,17 @@ public List<CategoryDto> getAllCategories() {
4444
return categories.stream().map((category) -> modelMapper.map(category, CategoryDto.class))
4545
.collect(Collectors.toList());
4646
}
47+
48+
@Override
49+
public CategoryDto updateCategory(CategoryDto categoryDto, Long categoryId) {
50+
Category category = categoryRepository.findById(categoryId).orElseThrow(
51+
() -> new ResourceNotFoundException("Category", "id", categoryId));
52+
53+
category.setName(categoryDto.getName());
54+
category.setDescription(categoryDto.getDescription());
55+
56+
Category updatedCategory = categoryRepository.save(category);
57+
58+
return modelMapper.map(updatedCategory, CategoryDto.class);
59+
}
4760
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /