kotlin 中的 JPA 错误:类"学生"应该有 [公共的、受保护的] 无参数构造函数



有人知道我如何解决这个问题吗:"class"Student"应该有[public,protected]no arg constructor"?

它在抱怨与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 = "",
)

永远不要将数据类用于@Entities。它稍后会导致一系列问题。请遵循此处列出的最佳实践:https://www.jpa-buddy.com/blog/best-practices-and-common-pitfalls/.

您可以使用无arg编译器插件,它将添加"一个附加的零参数构造函数";。详细信息在链接中。

您只需要指定一个无args构造函数。最简单的方法是为所有参数设置默认值,重载构造函数:

@Entity class Event(
@Id
@GeneratedValue(strategy = GenerationType.AUTO) var id: Long = -1,
var title: String = "no title",
var descriptor: String = "no description" ) {
}

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

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

当您不为class A创建任何构造函数,而是从其他地方创建class A的对象时,时间编译器会在引擎盖下创建一个无参数构造函数&执行时没有错误。另一方面,当您创建了一个显式具有某些参数的构造函数,但没有显式创建任何无参数构造函数,并希望构造函数届时会为您创建一个构造函数时,它会给您带来编译错误。因此,当您创建具有一些参数的构造函数时,还需要在类中显式创建一个无参数构造函数。参考链接,可能有助于这里

  • 为什么我们在Java中需要默认的无参数构造函数?

  • https://www.quora.com/Is-it-possible-to-define-a-parameterized-constructor-for-a-class-without-defining-a-parameter-less-constructor-in-Java

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

@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()
)

最新更新