@OneToMany 和 @ManyToOne Jpa

问题描述

在我的 Spring JPA 项目中,我有两个实体,Task 和 Developer。 List 可以分配给一个 Developer,一个 Task 只能有一个 Developer。我映射了它们:

开发人员

@Entity
@Table(name = "DEVELOPER")
public class Developer implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String name;

    @OnetoMany(targetEntity = Task.class,mappedBy = "developer",cascade=CascadeType.ALL,fetch = FetchType.LAZY)
    private List<Task> taskList;

任务

@Entity
@Table(name = "TASK")
public class Task implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long taskId;
    private String taskTitle;

    @ManyToOne
    @JoinColumn(name="developer_id")
    private Developer developer;

当我将任务列表分配给开发人员时,JSON 格式为:

{
    "id": 1,"name": "John","taskList": [
        {
            "taskId":2,"taskTitle": "Do sth"
        }
        ]
}

但是上面Task对象中Developer的值为null:

{
  "taskId":2,"taskTitle": "Do sth","developer": null
}

我希望这个开发者属性不为空,并且开发者和任务有双向关系。 我该如何解决这个问题?我是 Spring 和 Hibernate 的新手。任何帮助将不胜感激。

解决方法

@ManyToOne 注释中可能缺少 cascade=CascadeType.ALL,在 Java 文档中,它说:(Optional) The operations that must be cascaded to the target of the association.By default no operations are cascaded.enter image description here

,

去掉Developer类中的cascade=CascadeType.ALL,添加@joinColumn注解,就可以了。

开发者类看起来像这样-

@Entity
@Table(name = "DEVELOPER")
public class Developer implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;

@OneToMany(targetEntity = Task.class,mappedBy = "developer",fetch = FetchType.LAZY)
@JoinColumn(name="task_developer_id")
private List<Task> taskList;