英文:
Spring Data JPA: How to join two entities using annotations
问题
我有两个实体(Student和Project),想要通过外键"student_id"将它们连接起来。
@Entity
@Data
public class Project {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String title;
private Long student_id;
}
@Entity
@Data
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@OneToMany
private List<Project> projects;
}
简单来说,当我向Student存储库发送GET请求时,我想要获得带有项目列表的学生。
例如;
// > 用于POST到Project的JSON
{
"title":"java",
"student_id":1
}
// > 用于POST到Student的JSON
{
"name":"Bill Gates"
}
当我向Student发送GET请求时,我希望看到的内容如下;
[
{
"id":1,
"name":"java",
"projects":[
{
"id":1,
"title":"java"
}
]
}
]
是否可以只使用JPA注解来实现?提前感谢。
英文:
I have two entities(Student and Project) and want to join them by foreign key "student_id"
@Entity
@Data
public class Project {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String title;
private Long student_id;
}
@Entity
@Data
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@OneToMany
private List<Project> projects;
}
Simply, I want to get students with project list when I send GET request to Student repository.
For example;
// > json for POST to Project
{
"title":"java",
"student_id":1
}
// > json for POST to Student
{
"name":"Bill Gates"
}
What I expect to see when I send GET request to Student is simply like this below;
[
{
"id":1,
"name":"java",
"projects":[
{
"id":1,
"title":"java"
}
]
}
]
Is it applicable using only JPA annotations? Thanks in advance.
答案1
得分: 0
是的,这是适用的。
首先,在你的Project类中,你需要将student_id更改为student类,像这样:
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name = "student_id",nullable = false)
private Student student;
其次,你需要在你的oneToMany注解中添加'map'参数:
@OneToMany(mappedBy = "student")
private List<Project> projects;
就是这样。
另外注意:如果多名学生可以分配给同一个项目,你还可以考虑多对多的关系。
英文:
Yes, it's applicable.
First, you need to change the student_id to student class like this in your Project class
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name = "student_id",nullable = false)
private Student student;
Second, you need to add 'map' parameter to you oneToMany annotation
@OneToMany(mappedBy = "student")
private List<Project> projects;
and that's it.
Side note: you can also consider manytomany relationship if more than one student can be assigned to the same project
专注分享java语言的经验与见解,让所有开发者获益!
评论