JAVA/Spring Boot
스프링 게시판 데이터 전송( h2-console 사용 )
ri5
2021. 3. 10. 17:04
h2-console로 데이터를 저장하고 게시판 데이터를 josn 형태로 확인하는 과정까지 개발
postApiController.class
package com.jojoldu.book.springboot.web;
import com.jojoldu.book.springboot.service.posts.PostsService;
import com.jojoldu.book.springboot.web.dto.PostsResponseDto;
import com.jojoldu.book.springboot.web.dto.PostsSaveRequestDto;
import com.jojoldu.book.springboot.web.dto.PostsUpdateRequestDto;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
@RequiredArgsConstructor //초기화 되지않은 final 필드나 @notnull이 붙은 필드에 생성자를 생성
@RestController //뷰페이지가 따로 필요없이 결과만 도출한다.
public class PostApiController {
private final PostsService postsService;
@PostMapping("/api/v1/posts") // @RequestBody 어노테이션을 이용하면 HTTP 요청 Body를 자바 객체로 저장.
public long save(@RequestBody PostsSaveRequestDto requestDto){
return postsService.save(requestDto);
}
@PutMapping("/api/v1/posts/{id}") //기존의 Mapping 정보를 수정하는데 사용.
public long update(@PathVariable Long id, @RequestBody PostsUpdateRequestDto requestDto){
return postsService.update(id, requestDto);
}
@GetMapping("/api/v1/posts/{id}") //특정 핸들링 메서드에 매핑하기위하
public PostsResponseDto findById(@PathVariable Long id){
return postsService.findById(id);
}
}
컨트롤러를 통해서 매핑시키고 url을 통해 id를 조회
PostService.class
package com.jojoldu.book.springboot.service.posts;
import com.jojoldu.book.springboot.domain.posts.PostsRepository;
import com.jojoldu.book.springboot.domain.posts.Posts;
import com.jojoldu.book.springboot.web.dto.PostsResponseDto;
import com.jojoldu.book.springboot.web.dto.PostsSaveRequestDto;
import com.jojoldu.book.springboot.web.dto.PostsUpdateRequestDto;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
@RequiredArgsConstructor //초기화 되지않은 final 필드나 @notnull이 붙은 필드에 생성자를 생성
@Service
public class PostsService {
private final PostsRepository postsRepository;
@Transactional
public long save(PostsSaveRequestDto requestDto){
return postsRepository.save(requestDto.toEntity()).getId();
}
@Transactional
public Long update(Long id, PostsUpdateRequestDto requestDto){
Posts posts = postsRepository.findById(id).orElseThrow(() ->
new IllegalArgumentException("해당 게시글이 없습니다. id=" + id));
posts.update(requestDto.getTitle(), requestDto.getContent());
return id;
}
public PostsResponseDto findById (long id) {
System.out.print("아이디는" + id);
Posts entity = postsRepository.findById(id).orElseThrow(() -> new IllegalArgumentException("해당 게시글이 없습니다. id=" + id));
return new PostsResponseDto(entity);
}
}
findById메서드를 통해서 디비 검색하고 데이터가 없으면 게시글이 없다고 로그를 띄어줌.