![](/img/trans.png)
[英]How to make unidirectional @oneToMany relationship for 2 tables using JPA and Hibernate
[英]OneToMany relationship in hibernate creates 4 tables
我有一個問題。 我有兩個類具有相同的@OneToMany關系。 Hibernate創建4個表:product,product_categorie,categorie,categorie_product。
就我而言,我只需要3個表:product,categorie和product_categorie。
這是我的類圖:
我用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個或更多產品
我在代碼中做錯了嗎?
這是我第一次使用休眠模式,希望您能理解。
亞當,
您需要的是ManyToMany關系,而不是OneToMany。 與JoinTable一起映射產品和類別之間的關系。
@Entity
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int product_id;
private String naam;
private String omschrijving;
private double prijs;
@OneToMany(mappedBy = "product_m")
private List<Aanbieding> aanbiedingen;
@ManyToMany(cascade = { CascadeType.ALL })
@JoinTable(
name = "product_categories",
joinColumns = { @JoinColumn(name = "product_id") },
inverseJoinColumns = { @JoinColumn(name = "categorie_id") }
)
private List<Categorie> categories;
}
@Entity
public class Categorie {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int categorie_id;
private String naam;
private String omschrijving;
@ManyToMany(mappedBy = "categories")
private List<Product> producten;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.