我正在使用带有 Kotlin 的 Spring Boot/Spring Data 编写一个非常简单的 REST API。基本思想是一个人可以有很多本书。所以我想在我想要创建、咨询等的地方进行 CRUD 操作。我正在使用 H2 数据库,我已经为 4 个人订阅了 2 本书。我已经能够检索存储在数据库中的所有人员,并且我还可以通过 findAll() 和 findById(id) 方法从数据库中检索一个人,但是当我尝试 save()、delete() 或update() 我正面临一个 ConstraintViolationException。根据教程,我在 PersonEntity 类中创建了@ManyToOne,并在 BookEntity 类中使用了@OneToMany,并带有@JoinColumn 注释,但我在这部分有点迷失了......
尝试删除存储在数据库中的特定人员时出现此错误。这是错误和代码。如果你们对此有任何提示,我真的很感激。谢谢!
-> org.h2.jdbc.JdbcSQLIntegrityConstraintViolationException: Referential integrity constraint violation: "CONSTRAINT_8C: PUBLIC.PERSON FOREIGN KEY(BOOK_ID) REFERENCES PUBLIC.BOOK(BOOK_ID) (1)"; SQL statement:
delete from book where book_id=? [23503-200]
@Entity
@Table(name = "PERSON")
class PersonEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
val person_id : Long = 0L
@Column(name="name", nullable = false)
var name : String = ""
@Column(name="email", nullable = false)
var email : String = ""
@OneToMany(cascade = [(CascadeType.ALL)], fetch = FetchType.LAZY, mappedBy = "person_id", orphanRemoval = true)
var books : List<BookEntity?> = ArrayList()
}
----
@Entity
@Table(name = "BOOK")
class BookEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
var book_id : Long = 0L
@Column(name="title", nullable = false)
var title : String = ""
@Column(name="author", nullable = false)
var author : String = ""
@Column(name="publishing_company", nullable = false)
var publishingCompany : String = ""
@Column(name="publishing_year", nullable = false)
var publishingYear : String = ""
@Column(name="location", nullable = false)
var location : String = ""
@ManyToOne(fetch = FetchType.EAGER, optional = false)
@JoinColumn(name = "person_id", nullable = false)
@JsonIgnore
private var person_id : PersonEntity? = PersonEntity()
}
--