Kotlin中的JPA错误:类别'Student'应该有[public,protected]无参数建构函式

qgelzfjb  于 2022-11-30  发布在  Kotlin
关注(0)|答案(4)|浏览(122)

有没有人知道我怎样才能解决这个问题:'类别'Student'应该有[public,protected]无参数建构函式'?
它在抱怨与SchoolLesson的关系

import javax.persistence.Entity
import javax.persistence.GeneratedValue
import javax.persistence.GenerationType
import javax.persistence.Id
import javax.persistence.JoinColumn
import javax.persistence.ManyToOne

@Entity
data class Student(
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    val id: Long = -1,

    @ManyToOne
    @NotNull
    @JoinColumn(name = "school_lesson_id", referencedColumnName = "id")
    val report: SchoolLesson,

)

EDIT根据请求添加了SchoolLesson

import javax.persistence.*
    import javax.validation.constraints.NotNull

    @Entity
    data class SchoolLesson(
      @Id
      @GeneratedValue(strategy = GenerationType.IDENTITY)
      @Column(nullable = false)
      val id: Long = -1,
    
      @NotNull
      val name: String = "",
    )
n6lpvg4x

n6lpvg4x1#

千万不要对@实体使用数据类。这会在以后导致一系列问题。请遵循下面列出的最佳做法:https://www.jpa-buddy.com/blog/best-practices-and-common-pitfalls/

eaf3rand

eaf3rand2#

你可以使用无参数编译器插件,它将添加“一个额外的零参数构造函数”。

41ik7eoe

41ik7eoe3#

不要使用@Data,而是声明所有必要的注解来生成所需的内容。在这种情况下:

@Entity
@Getter
@Setter
@RequiredArgsConstructor
@NoArgsConstructor
public class SchoolLesson {
flmtquvp

flmtquvp4#

您可以为所有数据类属性提供默认值:

@Entity
data class Student(
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    val id: Long = -1,

    @ManyToOne
    @NotNull
    @JoinColumn(name = "school_lesson_id", referencedColumnName = "id")
    val report: SchoolLesson = SchoolLesson()
)

相关问题