简体   繁体   English

JPA一对多关系映射

[英]JPA One-To-Many Relationship Mapping

I am new in Spring Boot and I have a class Student.java and another Project.java. 我是Spring Boot的新手,我有一个Student.java类和另一个Project.java。 Each student can have multiple projects (the relationship is 1:M). 每个学生可以有多个项目(关系是1:M)。 I want to map them, and I have the following: 我想映射它们,我有以下内容:

In Student.java : 在Student.java中:

@OneToMany(mappedBy="student")
private List of projects;

In Project.java : 在Project.java中:

@ManyToOne <br>
@JoinColumn(name=student_id)
private Student student; 

I know that @JoinColumn adds a column in the project table in the database, but I don't understand what does mappedBy do? 我知道@JoinColumn在数据库的项目表中添加了一列,但我不明白mappedBy做了什么? I found this: " mappedBy indicates the entity is the inverse of the relationship. " What does the inverse of the relationship mean? 我发现了这一点:“ mappedBy表示实体是关系的反转。这种关系 的倒数意味着什么?

I tried the code in the database, and when I don't have the mappedBy I get 3 tables in the database (a different table that contains projectId and studentId), but I don't understand how that works. 我尝试了数据库中的代码,当我没有mappedBy时,我在数据库中得到3个表(一个包含projectId和studentId的不同表),但我不明白它是如何工作的。 Thanks for the help :) 谢谢您的帮助 :)

You can take a look at https://docs.oracle.com/javaee/6/api/javax/persistence/OneToMany.html#mappedBy() for more details. 您可以查看https://docs.oracle.com/javaee/6/api/javax/persistence/OneToMany.html#mappedBy()以获取更多详细信息。

The field that owns the relationship. 拥有这种关系的领域。 Required unless the relationship is unidirectional. 除非关系是单向的,否则是必需的。

It tells JPA to go around and find if is there any bean property with name student and use this configuration. 它告诉JPA四处寻找是否有任何名为student bean属性并使用此配置。 In your code, it will find a configuration in Project entity. 在您的代码中,它将在Project实体中找到配置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM