August 8, 2024

package com.kchabin.blog

import org.springframework.stereotype.Controller
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.ResponseBody

@Controller
class MainController {

    /*@GetMapping("/")
    fun index() : Unit {
        println("Hello World!")
    }*/

    @GetMapping("/blog")
    @ResponseBody
    fun index(): String {
        return "Kchabin's Blog"
    }
}

스크린샷 2024-08-08 오후 2.18.53.png

Post.kt

package com.kchabin.blog.entity

import jakarta.persistence.CascadeType
import jakarta.persistence.Column
import jakarta.persistence.Entity
import jakarta.persistence.GeneratedValue
import jakarta.persistence.GenerationType
import jakarta.persistence.Id
import jakarta.persistence.OneToMany
import java.time.LocalDateTime

@Entity
class Post(
    @Column(length = 200)
    var title: String,

    @Column(columnDefinition = "TEXT")
    var content: String,

    @Column
    var createDate: LocalDateTime,

    @OneToMany(mappedBy = "post", cascade = [CascadeType.REMOVE])
    var commentList: MutableList<Comment> = mutableListOf(),

    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    var id: Long? = null,
) {
    //JPA를 위한 기본 생성자
    constructor(): this("", "",LocalDateTime.now()) {}
}

Comment.kt

package com.kchabin.blog.entity

import jakarta.persistence.*
import java.time.LocalDateTime

@Entity
class Comment(
    @Column(columnDefinition = "TEXT")
    var content: String,

    @Column
    var createdAt: LocalDateTime,

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "post_id")
    var post: Post,

    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    var id: Long? = null
) {
    constructor() : this("", LocalDateTime.now(), Post()) {}
}

Post.kt에 Comment와의 연관관계 설정 중 오류 발생

스크린샷 2024-08-08 오후 2.43.21.png

[] 로 래핑해서 해결

@OneToMany(mappedBy = "post", cascade = [CascadeType.REMOVE])
var commentList: MutableList<Comment> = mutableListOf(),
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "post_id") //외래 키 컬럼 이름 명시
var post: Post,

ERD