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"
}
}
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()) {}
}
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와의 연관관계 설정 중 오류 발생
[]
로 래핑해서 해결
@OneToMany(mappedBy = "post", cascade = [CascadeType.REMOVE])
var commentList: MutableList<Comment> = mutableListOf(),
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "post_id") //외래 키 컬럼 이름 명시
var post: Post,