我试图定义两个类之间的双向关系。拥有方是类测验,相反方是用户。一个用户可以创建许多测验,而一个测验只能有一个创建它的用户。我在网上找到的每一个教程都指出,在owning方面,您指定了ManyToOne注释和JoinColumn,在相反的方面,您使用owners字段的名称指定了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'
}
Quiz.java
@Entity
@Table(name = "quizzes")
public class Quiz {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
...
@ManyToOne
@JoinColumn(name = "UserID")
private User createdBy;
}
@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;
}
这是我在网上找到的一个例子:https://www.logicbig.com/tutorials/java-ee-tutorial/jpa/map-with-entity-values.html
我认为你试图遵循的方法是不正确的。您不需要有一个map
对象来存储关联之间的键和相关实体。
简单的OneTomany
映射可以通过以下示例实现:
@Data
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true, mappedBy = "user")
private List<Quiz> quizzes = new ArrayList<>();
}
和
@Data
@Entity
@Table(name = "quizzes")
public class Quiz {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@JoinColumn(name = "user_id")
@ManyToOne(fetch = FetchType.LAZY)
@ToString.Exclude
private User user;
}