【问题标题】:How to design the spring boot JPA Model classes in below situation?如何在以下情况下设计 Spring Boot JPA 模型类?
【发布时间】:2020-07-12 06:56:13
【问题描述】:

我有一些目录,在这些目录下有一些类别,有些目录根本没有任何类别,最后在各个类别或目录下都有产品。

例如,目录家庭会有一个厨房类,然后会有烤箱、盘子、洗碗机等产品 等等,而产品床单将直接属于目录家庭,不属于任何类别

同样目录化学品没有任何类别,只有产品

下面的事情是确定的

i) 所有产品都属于某些目录

ii) 一些目录会有分类,然后分类会有产品

iii) 某些产品只属于目录,不会与任何类别关联

我想出了下面的模型类结构,但我不确定他们将如何处理上述情况,你能提出一些建议吗?

@Entity
public class Catalogs {

    @OneToMany(CascadeType.All, orphanRemoval = true)
    @JoinColumn(name = "catalogs_id")
    private Set<Categories> categories;

     /* rest of the code will go here */
}

我的分类类会是这样的

@Entity
public class Categories {
    
  @OneToMany(CascadeType.All, orphanRemoval = true)
  @JoinColumn(name = "categories_id")
    private Set<Products> products;  
}

最后我的 Products 课会变成这样

@Entity
public class Products {

     /* Products related codes */
}

我的目录类中是否也应该有一个产品字段? 如下所示

 @Entity
public class Catalogs {
    @OneToMany(CascadeType.All, orphanRemoval = true)
    @JoinColumn(name = "catalog_id")
    private Set<Categories> categories;

    @OneToMany(CascadeType.All, orphanRemoval = true)
    @JoinColumn(name = "catalog_id")
    private Set<Products> products;


     /* rest of the code will go here */
}

【问题讨论】:

  • 我发布了一个你可以查看的答案。

标签: spring hibernate jpa


【解决方案1】:

根据您的要求,我想到了一个方法。如果我从 Catalog 开始,我会将该类视为 root。然后我会将该类设计为

@Entity
public class Catalogs {

// just catalog name or other activity. not mapping

}

在那之后,我会设计这样的类别类,其中每个类别都在一个目录下。

@Entity
public class Categories {

// other attribute...
    
  @ManyToOne
  @JoinColumn(name = "catalog_id")
    private Catalogs catalogs;  
}

在这些之后,我会像这样设计我的产品类。正如您所说,一种产品可能在目录下,也可能在一个类别下。所以我让一些属性可以为空。

@Entity
public class Products {
    
    //other attributes....
    
    @ManyToOne
    @JoinColumn(name = "catalog_id")
    @Nullable
    private Catalogs catalogs;

    @ManyToOne
    @JoinColumn(name = "category_id")
    @Nullable
    private Categories categories;
}

检查这种方法。并回应您的意见。

【讨论】:

  • 非常感谢 Avijit Barua,我会试试这个并再次输入评论
  • @Gaurav,好的,尝试后告诉我。
  • 我给了你支持 Avijit 但不幸的是我的声誉不足以表明它:-)) 再次感谢你的详细回答:-)
猜你喜欢
  • 2019-01-26
  • 1970-01-01
  • 1970-01-01
  • 2018-07-12
  • 1970-01-01
  • 2020-12-23
  • 2012-10-31
  • 2018-11-26
  • 2019-10-22
相关资源
最近更新 更多