【问题标题】:@OneToMany and @ManyToOne Jpa@OneToMany 和 @ManyToOne Jpa
【发布时间】:2021-01-11 07:07:09
【问题描述】:

在我的 Spring JPA 项目中,我有两个实体,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
}

我希望这个 developer 属性不为 null 并且 Developer 和 task 具有双向关系。 我该如何解决这个问题?我是 Spring 和 Hibernate 的新手。任何帮助将不胜感激。

【问题讨论】:

    标签: spring-boot hibernate spring-data-jpa one-to-many many-to-one


    【解决方案1】:

    @ManyToOne 注释中可能缺少 cascade=CascadeType.ALL,而在 Java 文档中,它说:(Optional) The operations that must be cascaded to the target of the association.By default no operations are cascaded.https://docs.jboss.org/hibernate/jpa/2.1/api/javax/persistence/ManyToOne.html

    【讨论】:

      【解决方案2】:

      去掉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;
      

      【讨论】:

        猜你喜欢
        • 2016-11-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-02-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多