【发布时间】:2021-10-14 12:21:21
【问题描述】:
我正在尝试定义两个类之间的双向关系。拥有方是 Quiz 类,反之是 User。一个用户可以创建许多测验,而一个测验只能有一个用户创建它。我在网上找到的每个教程都指出,在拥有方指定 ManyToOne 注释和 JoinColumn,在相反方指定 OneToMany 和 mappedBy 以及所有者字段的名称。但是,当我这样做时,IDE 给我一个错误“找不到反比关系”。这个概念我哪里错了?任何帮助或指导将不胜感激。
build.gradle
plugins {
id 'org.springframework.boot' version '2.2.2.RELEASE'
id 'java'
id "io.freefair.lombok" version "6.1.0-m3"
}
apply plugin: 'io.spring.dependency-management'
sourceCompatibility = 11
repositories {
mavenCentral()
}
sourceSets.main.resources.srcDirs = ["src/resources"]
dependencies {
implementation 'org.springframework.boot:spring-boot-starter:2.5.3'
implementation 'org.springframework.boot:spring-boot-starter-actuator:2.5.3'
implementation 'org.springframework.boot:spring-boot-starter-web:2.5.3'
implementation 'org.springframework.boot:spring-boot-starter-data-jpa:2.5.3'
implementation 'org.springframework.boot:spring-boot-starter-security:2.5.3'
implementation 'org.springframework.boot:spring-boot-starter-validation:2.5.3'
runtimeOnly 'com.h2database:h2:1.4.200'
}
测验.java
@Entity
@Table(name = "quizzes")
public class Quiz {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
...
@ManyToOne
@JoinColumn(name = "UserID")
private User createdBy;
}
用户.java:
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
...
@OneToMany(mappedBy = "createdBy")
@MapKey(name = "id")
private HashMap<Integer, Quiz> quizzes;
}
我尝试更改为 Map 引用而不是 HashMap,将 targetEntity 选项添加到 OneToMany 注释并指向 Quiz.class,将显式 @Column(name = "[columnName]") 添加到每个类字段等。仍然是 IDE给我“找不到反比关系”的错误。我不明白我做错了什么。
这是我在网上找到的一个例子:https://www.logicbig.com/tutorials/java-ee-tutorial/jpa/map-with-entity-values.html
【问题讨论】:
标签: java spring-boot jpa orm