์นดํ…Œ๊ณ ๋ฆฌ ์—†์Œ

[JPA] ๊ธ€ ์ƒ์„ธ๋ณด๊ธฐ(์กฐํšŒ) API ๊ตฌํ˜„ - 6

๋ฏธ๋กœ910 2024. 10. 2. 12:46
๐Ÿ’ก
1. Optional<T> ์— ๋Œ€ํ•œ ๊ฐœ๋…์„ ์ˆ™์ง€ ํ•œ๋‹ค.
2. ๊ฒฝ๋กœ ๋ณ€์ˆ˜(Path variable)์— ๋Œ€ํ•œ ๊ฐœ๋…์„ ์ดํ•ดํ•˜๊ณ  ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค.

 

BlogService ํŒŒ์ผ์— ๊ฒŒ์‹œ๊ธ€ ์กฐํšŒ ๋กœ์ง ์ถ”๊ฐ€ - 1
@RequiredArgsConstructor
@Service // IoC (๋นˆ์œผ๋กœ ๋“ฑ๋ก)
public class BlogService {
	
	//@Autowired // DI <-- ๊ฐœ๋ฐœ์ž๋“ค์ด ๊ฐ€๋…์„ฑ ๋•Œ๋ฌธ์— ์ž‘์„ฑ์„ ํ•ด์ค€๋‹ค.
	private final PostRepository postRepository;
	
	@Transactional // (์ž‘์—…์˜ ๋‹จ์œ„) // ์“ฐ๊ธฐ ์ง€์—ฐ ์ฒ˜๋ฆฌ๊นŒ์ง€
	public Article save(ArticleDTO dto) {
		// ๋น„์ฆˆ๋‹ˆ์Šค ๋กœ์ง์ด ํ•„์š”ํ•˜๋‹ค๋ฉด ์ž‘์„ฑ...
		return postRepository.save(dto.toEntity());
	}
	
	// ์ „์ฒด ๊ฒŒ์‹œ๊ธ€ ์กฐํšŒ ๊ธฐ๋Šฅ
	public List<Article> findAll(){
		List<Article> articles = postRepository.findAll();
		
		return articles;
	}
	
	// ์ƒ์„ธ ๋ณด๊ธฐ ๊ฒŒ์‹œ๊ธ€ ์กฐํšŒ
	public Article findById(Integer id) {
		// Optional<T>๋Š” Java 8์—์„œ ๋„์ž…๋œ ํด๋ž˜์Šค์ด๋ฉฐ,
		// ๊ฐ’์ด ์กด์žฌํ•  ์ˆ˜๋„ ์žˆ๊ณ  ์—†์„ ์ˆ˜๋„ ์žˆ๋Š” ์ƒํ™ฉ์„ ๋ช…ํ™•ํ•˜๊ฒŒ ์ฒ˜๋ฆฌํ•˜๊ธฐ ์œ„ํ•ด ์‚ฌ์šฉ๋ฉ๋‹ˆ๋‹ค.
      return postRepository.findById(id).orElseThrow(() -> new Exception400("ํ•ด๋‹น ๊ฒŒ์‹œ๊ธ€์ด ์—†์Šต๋‹ˆ๋‹ค."));
	}

	
	
}

Optional<T> (Optional์„ ์‚ฌ์šฉํ•˜์—ฌ null ์ฒ˜๋ฆฌ๋ฅผ ์•ˆ์ „ ์ฒ˜๋ฆฌ ํ•˜๊ธฐ ์œ„ํ•จ)

  • ๊ฐ’์ด ์กด์žฌํ•  ๋•Œ: Optional ์•ˆ์— ๊ฐ’์ด ํฌํ•จ๋˜์–ด ์žˆ์œผ๋ฉฐ, ์ด ๊ฐ’์„ ์•ˆ์ „ํ•˜๊ฒŒ ๊บผ๋‚ด์–ด ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.
  • ๊ฐ’์ด ์—†์„ ๋•Œ: Optional์ด ๋น„์–ด ์žˆ์œผ๋ฉฐ, ์ด๋ฅผ ํ†ตํ•ด null์„ ์ง์ ‘ ์ฒ˜๋ฆฌํ•˜๋Š” ๋Œ€์‹ , ๋‹ค์–‘ํ•œ ๋ฉ”์„œ๋“œ๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ๋น„์–ด์žˆ๋Š” ์ƒํ™ฉ์„ ์ฒ˜๋ฆฌํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

 

BlogApiController
@RequiredArgsConstructor
@RestController // @controller + @responsebody
public class BlogApiController {
	
	private final BlogService blogService;
		
	// URL , ์ฆ‰, ์ฃผ์†Œ ์„ค๊ณ„ - http://localhost:8080/api/article
	@PostMapping("/api/articles")
	public ResponseEntity<Article> addArticle(@RequestBody ArticleDTO dto) {
		// 1. ์ธ์ฆ ๊ฒ€์‚ฌ
		// 2. ์œ ํšจ์„ฑ ๊ฒ€์‚ฌ 
		Article savedArtilce = blogService.save(dto);
		return ResponseEntity.status(HttpStatus.CREATED).body(savedArtilce);
	}
	
	
	// URL , ์ฆ‰, ์ฃผ์†Œ ์„ค๊ณ„ - http://localhost:8080/api/articles
	@GetMapping(value = "/api/articles", produces = MediaType.APPLICATION_JSON_VALUE)
	public ApiUtil<?> getAllArticles() {
		List<Article> articles = blogService.findAll();
		if(articles.isEmpty()) {
			// return new ApiUtil<>(new Exception400("๊ฒŒ์‹œ๊ธ€์ด ์—†์Šต๋‹ˆ๋‹ค."));
			throw new Exception400("๊ฒŒ์‹œ๊ธ€์ด ์—†์Šต๋‹ˆ๋‹ค.");
		}
		return new ApiUtil<>(articles);
	}
	
	// URL , ์ฆ‰, ์ฃผ์†Œ ์„ค๊ณ„ - http://localhost:8080/api/articles/1
	@GetMapping(value = "/api/articles/{id}")
	public ApiUtil<?> findArtilcle(@PathVariable(name = "id") Integer id) {
		
		// 1. ์œ ํšจ์„ฑ ๊ฒ€์‚ฌ ์ƒ๋žต
 		Article article = blogService.findById(id);
		return new ApiUtil<>(article);
	}
	
}

 

์‹คํ–‰ ํ™”๋ฉด_____