hibernate中的OneToMany关系创建4个表

我有问题。我有两个具有相同@OneToMany 关系的类。Hibernate 创建 4 个表:product、product_categorie、categorie、categorie_product。

在我的情况下,我只需要 3 个表:product、categorie 和 product_categorie。

这是我的类图:

http://img4.mukewang.com/62a946d500013ede06460149.jpg

我用Java编写的代码:


@Entity

public class Product {

    @Id

    @GeneratedValue(strategy = GenerationType.IDENTITY)

    private int product_id;

    private String naam, omschrijving;

    private double prijs;

    @OneToMany(mappedBy = "product_m")

    private List<Aanbieding> aanbiedingen;

    @OneToMany

    private List<Categorie> categories;

}


@Entity

public class Categorie {

    @Id

    @GeneratedValue(strategy = GenerationType.IDENTITY)

    private int categorie_id;

    private String naam, omschrijving;

    @OneToMany

    private List<Product> producten;


}

就我而言,我需要归档以下内容:


一件产品属于 1 个或多个类别


一个类别包含 0 个或多个产品


我在代码中做错了吗?


这是我第一次使用hibernate,希望你能理解。


catspeake
浏览 88回答 1
1回答

素胚勾勒不出你

您需要的是多对多关系,而不是单对多关系。与 JoinTable 一起映射产品和类别之间的关系。@Entitypublic class Product {&nbsp; &nbsp; @Id&nbsp; &nbsp; @GeneratedValue(strategy = GenerationType.IDENTITY)&nbsp; &nbsp; private int product_id;&nbsp; &nbsp; private String naam;&nbsp; &nbsp; private String omschrijving;&nbsp; &nbsp; private double prijs;&nbsp; &nbsp; @OneToMany(mappedBy = "product_m")&nbsp; &nbsp; private List<Aanbieding> aanbiedingen;&nbsp; &nbsp; @ManyToMany(cascade = { CascadeType.ALL })&nbsp; &nbsp; @JoinTable(&nbsp; &nbsp; &nbsp; &nbsp; name = "product_categories",&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; joinColumns = { @JoinColumn(name = "product_id") },&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; inverseJoinColumns = { @JoinColumn(name = "categorie_id") }&nbsp; &nbsp; )&nbsp; &nbsp; private List<Categorie> categories;}@Entitypublic class Categorie {&nbsp; &nbsp; @Id&nbsp; &nbsp; @GeneratedValue(strategy = GenerationType.IDENTITY)&nbsp; &nbsp; private int categorie_id;&nbsp; &nbsp; private String naam;&nbsp; &nbsp; private String omschrijving;&nbsp; &nbsp; @ManyToMany(mappedBy = "categories")&nbsp; &nbsp; private List<Product> producten;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java