[Kotlin+Spring] 간단한 CRUD 해보기 2

치미·2022년 6월 6일
post-thumbnail

프로젝트 구조



Model Mapper 설정

config안 AppConfig에 ModelMapper를 설정해 주었다.
이렇게 따로 설정해 주는 이유는 매번 설정하는 걸 방지하기 위함!

import org.modelmapper.ModelMapper
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration

@Configuration
class AppConfig{

    @Bean
    fun modelMapper(): ModelMapper {
        val modelMapper = ModelMapper()
        modelMapper.configuration.isFieldMatchingEnabled = true
        return modelMapper
    }
}

Board Entity

Board.kt

import com.example.exec.dto.BoardFormDto
import javax.persistence.Entity
import javax.persistence.GeneratedValue
import javax.persistence.GenerationType
import javax.persistence.Id

@Entity
class Board (
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    var id: Long? = null,
    var writer: String, //작성자
    var password: String, //암호
    var title: String, //글 제목
    var content: String //글 내용
    ){

    fun updatePost(boardFormDto: BoardFormDto){ //글 수정할 때
        writer = boardFormDto.writer
        title = boardFormDto.title
        password = boardFormDto.password
        content = boardFormDto.content
    }

}

우선 model폴더 안에 Entity를 만들어 준다.
updatePost()는 글을 수정할 때 사용해줄 함수다.

Board Repository

만들었으면 이제 JpaRepository를 상속받아 Repository를 만들어 준다.
BoardRepository.kt

import com.example.exec.model.Board
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.stereotype.Repository

@Repository
interface BoardRepository: JpaRepository<Board, Long> {
}

BoardService

/service/BoardService.kt

import com.example.exec.dto.BoardFormDto
import com.example.exec.model.Board
import com.example.exec.repository.BoardRepository
import org.modelmapper.ModelMapper
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service

@Service
class BoardService @Autowired constructor(
    val boardRepository: BoardRepository,
    val modelMapper: ModelMapper
) {

    fun save(boardFormDto: BoardFormDto): Long? {
        return boardRepository.save(modelMapper.map(boardFormDto, Board::class.java)).id
    }

    fun getPost(id: Long): Board? {
        return boardRepository.findById(id).get()
    }

    fun deletePost(id: Long) {
        boardRepository.deleteById(id)
    }

    fun updatePost(id: Long, boardFormDto: BoardFormDto): Board {
        val post = boardRepository.findById(id).get()
        post.updatePost(boardFormDto)
        return post
    }

    fun getPostList(): List<Board> {
        return boardRepository.findAll()
    }

}

DTO 만들기

계층간 데이터를 주고 받기 위해서 DTO 만들어주기!

/dto/BoardFormDto.kt

data class BoardFormDto (
    var writer: String,
    var password: String,
    var title: String,
    var content: String
        ){
}

Board Controller

/controller/BoardController.kt

import com.example.exec.dto.BoardFormDto
import com.example.exec.service.BoardService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.*

@RestController //REST API
@RequestMapping("board")
class BoardController @Autowired constructor(val boardService: BoardService) {

	//게시글 등록
    @PostMapping
    fun addPost(boardFormDto: BoardFormDto): ResponseEntity<Any> {
        val save = boardService.save(boardFormDto)
        return ResponseEntity.ok().body(save)
    }
	
    //게시글 읽기
    @GetMapping("/{id}")
    fun getPost(@PathVariable id: Long): ResponseEntity<Any> {
        val post = boardService.getPost(id)
        return ResponseEntity.ok().body(post)
    }

	//게시글 삭제
    @DeleteMapping("/{id}")
    fun deletePost(@PathVariable id: Long): ResponseEntity<Any> {
        boardService.deletePost(id)
        return ResponseEntity.ok().body(true)
    }

	//게시글 수정
    @PutMapping("/{id}")
    fun updatePost(
        @PathVariable id: Long,
        boardFormDto: BoardFormDto
    ): ResponseEntity<Any> {
        val post = boardService.updatePost(id, boardFormDto)
        return ResponseEntity.ok().body(post)

    }

	//게시글 목록
    @GetMapping("/list")
    fun listPost(): ResponseEntity<Any> {
        return ResponseEntity.ok().body(boardService.getPostList())
    }

}

이렇게 간단히 CURD를 구현해보았다!
postman으로 확인해보면 잘 동작하는 것을 확인할 수 있다.
profile
backend developer

0개의 댓글