我试图在 Kotlin 中使用注解定义一个简单的 Hibernate 映射。但是我的多对多关系并没有按照预期工作,导致 IntelliJ IDEA 显示以下错误:
'one to many'/'many to many' 属性值类型不应为 '? extends PersonAddress/Person'
我的代码库:
@Entity
open class Person(
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
var id: Long = 0L,
@OneToMany(mappedBy = "person")
var addresses: Set<PersonAddress> = setOf() //Fail
)
@Entity
open class Address(
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
var id: Long = 0L,
@OneToMany(mappedBy = "address")
var persons: Set<PersonAddress> = setOf() //Fail
)
@Entity
open class PersonAddress(
@Id
var id: Long,
@ManyToOne
@JoinColumn(name = "person_id")
var person: Person,
@ManyToOne
@JoinColumn(name = "address_id")
var address: Address
) : Serializable
因为我认为这可能是由于联接表引起的错误,所以我尝试对ManyToMany
关系做相同的操作:
@ManyToMany(mappedBy = "addresses")
var persons: Set<Person> = setOf()
但是这里发生了同样的错误。
Application.kt
@SpringBootApplication
class Application {
fun main(args: Array<String>) {
runApplication<Application>(*args)
}
}
构建.gradle.kts
plugins {
java
id("org.springframework.boot") version "2.2.5.RELEASE"
id("io.spring.dependency-management") version "1.0.9.RELEASE"
kotlin("jvm")
kotlin("plugin.spring") version "1.3.70"
kotlin("plugin.jpa")
kotlin("plugin.allopen") version "1.3.70"
}
val developmentOnly by configurations.creating
configurations {
runtimeClasspath {
extendsFrom(developmentOnly)
}
}
repositories {
mavenCentral()
}
dependencies {
implementation("org.springframework.boot:spring-boot-starter-data-jpa")
implementation("org.springframework.boot:spring-boot-starter-validation")
implementation("org.jetbrains.kotlin:kotlin-reflect")
implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8")
runtimeOnly("com.h2database:h2")
developmentOnly("org.springframework.boot:spring-boot-devtools")
testImplementation("org.springframework.boot:spring-boot-starter-test") {
exclude(group = "org.junit.vintage", module = "junit-vintage-engine")
}
}
allOpen {
annotation("javax.persistence.Entity")
annotation("javax.persistence.Embeddable")
annotation("javax.persistence.MappedSuperclass")
}
configure<JavaPluginConvention> {
sourceCompatibility = JavaVersion.VERSION_1_8
}
tasks {
compileKotlin {
kotlinOptions.jvmTarget = "1.8"
}
compileTestKotlin {
kotlinOptions.jvmTarget = "1.8"
}
}
tasks.withType<org.jetbrains.kotlin.gradle.tasks.KotlinCompile> {
kotlinOptions {
freeCompilerArgs = listOf("-Xjsr305=strict")
jvmTarget = "1.8"
}
}
tasks.withType<Test> {
useJUnitPlatform()
}
编辑1: 我通过使用以下方式解决了错误:
var persons: MutableList<PersonAddress> = mutableListOf()
然而,当我检查我的代码时,错误发生在昨天运行良好的属性上。