【发布时间】:2020-05-08 21:54:43
【问题描述】:
我在 kotlin 中有两个不同的小项目,一个是映射工作的(我不使用数据类),另一个是映射不起作用的。
工作示例 预订
@Entity
class Book() {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
var id: Int? = null
var name: String? = null
@ManyToMany(cascade = [CascadeType.PERSIST, CascadeType.MERGE])
@JoinTable(name = "BOOK_AUTHOR", joinColumns = [JoinColumn(name = "BOOK_ID", referencedColumnName = "ID")], inverseJoinColumns = [JoinColumn(name = "AUTHOR_ID", referencedColumnName = "ID")])
private var authors: MutableSet<Author> = HashSet()
// constructor(name: String?, authors: Set<Author>) : this() {
// this.name = name
//
// setAuthors(authors)
// }
fun getAuthors(): Set<Author> {
return authors
}
fun setAuthors(authors: Set<Author>) {
for (author in authors) {
author.books.add(this)
this.authors.add(author)
}
}
}
作者
@Entity
class Author() {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
var id: Int? = null
var name: String? = null
@ManyToMany(mappedBy = "authors")
val books: MutableSet<Book> = HashSet<Book>()
// constructor(name: String?) : this() {
// this.name = name
// }
}
现在那个不工作了,有数据类
书
@Entity
data class Book (
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
val id:Int,
var name:String,
@ManyToMany(cascade = [CascadeType.PERSIST, CascadeType.MERGE])
@JoinTable(name = "BOOK_AUTHOR", joinColumns = [JoinColumn(name = "BOOK_ID", referencedColumnName = "ID")], inverseJoinColumns = [JoinColumn(name = "AUTHOR_ID", referencedColumnName = "ID")])
private var authors: MutableSet<Author> = HashSet()
){
constructor() : this(-1,"", mutableSetOf()) {}
// constructor(name: String) : this() {
// this.name = name
// authors = HashSet()
// }
constructor(name: String, authors: Set<Author>) : this() {
this.name = name
//this.authors = authors;
setAuthors(authors)
}
fun getAuthors(): Set<Author> {
return authors
}
fun setAuthors(authors: Set<Author>) { //this.authors = authors;
//add relations manually
for (author in authors) {
author.books.add(this)
this.authors.add(author)
}
}
override fun toString(): String {
return "heya"
}
}
作者
@Entity
data class Author(
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
val id:Int,
var name:String,
@ManyToMany(mappedBy = "authors")
val books: MutableSet<Book> = HashSet<Book>()
){
constructor() : this(-1,"", mutableSetOf()) {}
constructor(name: String) : this() {
this.name = name
}
override fun toString(): String {
return "heya"
}
}
现在我可以在第一个示例中使用它,但我不使用 kotlin 提供的数据类,我不确定这是否重要, here 提到部分功能将不可用。
其次,我想了解数据类映射工作需要什么,因为现在它总是抛出堆栈溢出错误,
【问题讨论】:
标签: jpa kotlin spring-data-jpa spring-data