同时保存孩子和父母

时间:2019-03-23 11:03:51

标签: spring kotlin relationship

我需要在交易中同时保存2个模型,但是...

org.postgresql.util.PSQLException: ERROR: null value in column "book_id" violates not-null constraint

我不明白怎么了。我的模特:

a)章节

@Entity
class Chapter() : AuditModel() {

constructor(number: Int, title: String) : this() {
    this.number = number
    this.title = title
}

@Column(nullable = false)
var number: Int? = null

@Column(nullable = false)
lateinit var title: String

@Column(nullable = false)
var progress: Int = 0

@ManyToOne
@JoinColumn(name = "book_id")
lateinit var book: Book
}

b)本书

@Entity
class Book() : AuditModel() {

constructor(title: String, author: String) : this() {
    this.title = title
    this.author = author
}

@Column(nullable = false)
lateinit var title: String

@Column(nullable = false)
lateinit var author: String

@OneToMany(mappedBy = "book", cascade = [CascadeType.PERSIST])
val chapters: MutableSet<Chapter> = HashSet()
}

保存模型的功能:

@Transactional
fun createBook(title: String, author: String): Boolean {
    val book = Book(title, author)
    val chapter = Chapter(1, "Example - 1")
    book.chapters.add(chapter)

    return bookRepository.save(book) != null
}

如何解决?我是春季的新手,这对我来说是完全不可理解的。

0 个答案:

没有答案
相关问题