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 4dede2f

Browse files
add: Get All Categories REST API
1 parent 8f1d1c5 commit 4dede2f

File tree

3 files changed

+23
-0
lines changed

3 files changed

+23
-0
lines changed

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

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@
77
import org.springframework.security.access.prepost.PreAuthorize;
88
import org.springframework.web.bind.annotation.*;
99

10+
import java.util.List;
11+
1012
@RestController
1113
@RequestMapping("/api/categories")
1214
public class CategoryController {
@@ -30,4 +32,10 @@ public ResponseEntity<CategoryDto> getCategory(@PathVariable("id") Long category
3032
CategoryDto categoryDto = categoryService.getCategory(categoryId);
3133
return ResponseEntity.ok(categoryDto);
3234
}
35+
36+
// build Get All Categories REST API
37+
@GetMapping
38+
public ResponseEntity<List<CategoryDto>> getCategories() {
39+
return ResponseEntity.ok(categoryService.getAllCategories());
40+
}
3341
}

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

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,12 @@
33
import com.springboot.blog.entity.Category;
44
import com.springboot.blog.payload.CategoryDto;
55

6+
import java.util.List;
7+
68
public interface CategoryService {
79
CategoryDto addCategory(CategoryDto categoryDto);
810

911
CategoryDto getCategory(Long categoryId);
12+
13+
List<CategoryDto> getAllCategories();
1014
}

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

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,9 @@
88
import org.modelmapper.ModelMapper;
99
import org.springframework.stereotype.Service;
1010

11+
import java.util.List;
12+
import java.util.stream.Collectors;
13+
1114
@Service
1215
public class CategoryServiceImpl implements CategoryService {
1316
private CategoryRepository categoryRepository;
@@ -33,4 +36,12 @@ public CategoryDto getCategory(Long categoryId) {
3336

3437
return modelMapper.map(category, CategoryDto.class);
3538
}
39+
40+
@Override
41+
public List<CategoryDto> getAllCategories() {
42+
List<Category> categories = categoryRepository.findAll();
43+
44+
return categories.stream().map((category) -> modelMapper.map(category, CategoryDto.class))
45+
.collect(Collectors.toList());
46+
}
3647
}

0 commit comments

Comments
(0)

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