java - Spring 数据JPA : How to join two entities using annotations

标签 java hibernate jpa spring-data-jpa spring-data

我有两个实体(学生和项目),想要通过外键加入它们“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;
}

简单地说,当我向学生存储库发送 GET 请求时,我希望获得学生的项目列表。

例如;

// > json for POST to Project
{
    "title":"java",
    "student_id":1
}
// > json for POST to Student
{
    "name":"Bill Gates"
}

当我向 Student 发送 GET 请求时,我期望看到的内容如下所示;

[
   {
      "id":1,
      "name":"java",
      "projects":[
         {
            "id":1,
            "title":"java"
         }
      ]
   }
]

仅使用 JPA 注释是否适用?提前致谢。

最佳答案

是的,它适用。 首先,您需要在项目类中将student_id更改为学生类

@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name = "student_id",nullable = false)
private Student student;

其次,您需要向 oneToMany 注释添加“map”参数

@OneToMany(mappedBy = "student")
private List<Project> projects;

就是这样。

旁注:如果可以将多个学生分配到同一项目,您还可以考虑多对多关系

关于java - Spring 数据JPA : How to join two entities using annotations,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62076667/

相关文章:

java - Hibernate:覆盖子类中的字段可选性

无论代理类型如何,java tcp ip socket编程

java - 自定义模型的缓存/持久化的最佳方法

java - 如何使用BigInteger值来初始化字符串数组?

java - Hibernate:从不同类路径的jar中自动加载标记为@Entity的类

java - org.springframework.dao.DataIntegrityViolationException : Duplicate entry Spring+Hibernate

java - Lombok - 访问 getter 不可见

hibernate - 无法在Kotlin和JpaRepository中为嵌套列表对象找到适当的构造函数错误

java - hibernate MaterializedClobType 存储长对象而不是文本

java - 显示 JSF 表中对象的数组列表