有谁知道我如何解决这个问题:'类'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,
)
#编辑根据要求添加了学校课程
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 = "",
)
您只需要指定一个无参数构造函数。最简单的方法是为所有参数设置默认值,重载构造函数:
@Entity class Event(
@Id
@GeneratedValue(strategy = GenerationType.AUTO) var id: Long = -1,
var title: String = "no title",
var descriptor: String = "no description" ) {
}
切勿将数据类用于@Entities。会导致以后出现一系列的问题。请遵循此处列出的最佳实践:https://www.jpa-buddy.com/blog/best-practices-and-common-pitfalls/。
您可以使用no-arg编译器插件,它将添加“一个额外的零参数构造函数”。详情请见链接。
不要使用@Data,而是声明所有必要的注释来生成您需要的内容。在这种情况下:
@Entity
@Getter
@Setter
@RequiredArgsConstructor
@NoArgsConstructor
public class SchoolLesson {
当您没有为
class A
创建任何构造函数,而是从其他位置创建 class A
的对象时,编译器会在底层创建一个无参数构造函数,并且执行时不会出错。另一方面,当您显式创建一个具有一些参数的构造函数,但不显式创建任何无参数构造函数,并希望构造函数将为您创建一个构造函数时,它会给您带来编译错误。因此,当您创建具有某些参数的构造函数时,您还需要在类中显式创建一个无参数构造函数。参考链接可能会有所帮助
我添加了 JPA 插件,问题就消失了
plugins {
val kotlinVersion = "1.9.22"
kotlin("plugin.jpa") version kotlinVersion
}
您可以为所有数据类属性提供默认值:
@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()
)