【问题标题】:How to correctly map a OneToMany relationship in Spring Boot?如何在 Spring Boot 中正确映射 OneToMany 关系?
【发布时间】:2020-02-08 18:14:04
【问题描述】:

您好,我正在开发一个 Spring Boot 项目,我有点困惑。我有一个Product 实体和一个Property 实体,它们看起来像这样:

public class Product {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column
    private Long id;

    @Column
    private String name;

    @OneToMany(cascade = CascadeType.ALL)
    private List<Property> properties;
//getters and setters omitted
}
public class Property {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column
    private Long id;

    @Column
    private String name;

    @Column
    private String value;
//getters and setters omitted
}

现在我想知道是否还需要在属性实体中指定一个多对一关系,或者这是否足够好?在我过去的项目中,我尝试在两个实体(biredctional)中使用关系,结果一团糟,因为我在尝试从前端检索数据时经常陷入数据的“无限循环”。我只需要一个单向且简单的关系,其中一个产品可以有多个属性,然后我可以使用 getProperties() 方法检索数据。我是不是理解错了,或者我的代码对我想要做的事情足够好?

【问题讨论】:

    标签: java spring hibernate


    【解决方案1】:

    如果你有一个单向的@OneToMany 关联,这意味着你只能从外键所在的父端访问关系。 More Details here

    双向关联应始终在两侧更新,因此父端应包含 addChild 和 removeChild 组合。这些方法确保我们始终同步关联的双方,以避免对象或关系数据损坏问题。

    【讨论】:

      【解决方案2】:

      如果您不需要从属性中检索产品,则无需映射多对一链接。 在我看来,编写你真正需要的代码总是一个好主意。

      没有普遍意义上的“好”实现,只有更适合您需求且最容易维护的解决方案。

      【讨论】:

        【解决方案3】:
        public class Product {
            @Id
            @GeneratedValue(strategy = GenerationType.AUTO)
            @Column
            private Long id;
        
            @Column
            private String name;
        
            @OneToMany(mappedBy = "product" ,cascade = CascadeType.ALL)
            private List<Property> properties;
        }
        
        
        public class Property {
            @Id
            @GeneratedValue(strategy = GenerationType.AUTO)
            @Column
            private Long id;
        
            @Column
            private String name;
        
            @Column
            private String value;
        
            @ManyToOne
            private Product prodcut;
        }
        

        您还应该注释关系的“很多”部分(@ManyToOne)。 您还应该在 Product 实体中指定 Property 实体将在 DB ( @OneToMany(mappedBy = "product" ,cascade = CascadeType.ALL)) 中进行映射。

        检查上面的代码是否有修改。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2021-09-23
          • 2012-02-08
          • 2022-01-03
          • 2013-11-20
          • 2020-06-26
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多