2 回答

TA貢獻(xiàn)1848條經(jīng)驗(yàn) 獲得超2個(gè)贊
您應(yīng)該考慮以下映射:
將 Long 用于 id 列,而不是 int - int 太小
雙向映射可能更好
有用于添加/刪除孩子的實(shí)用方法(如下面的代碼)
在實(shí)體類中初始化您的集合以避免空值
例子:
@Entity(name = "MyOrder")
@Table(name = "myorder")
public class MyOrder {
@Id
@GeneratedValue
private Long id;
@OneToMany(mappedBy = "myorder", cascade = CascadeType.ALL, orphanRemoval = true)
private List<Product> products = new ArrayList<>();
//Constructors, getters, setters etc.
public void addProduct(Product product) {
products.add(product);
product.setMyOrder(this);
}
public void removeProduct(Product product) {
products.remove(product);
product.setMyOrder(null);
}
}
@Entity(name = "Product")
@Table(name = "product")
public class Product {
@Id
@GeneratedValue
private Long id;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "myorder_id")
private MyOrder myOrder;
//Constructors, getters and setters
//equals and hashCode
}

TA貢獻(xiàn)1786條經(jīng)驗(yàn) 獲得超11個(gè)贊
您的更改沒有從父實(shí)體級(jí)聯(lián)到子實(shí)體,您需要將其添加到您的映射中:
@Entity
@Table(name = "MyOrder")
public class MyOrder {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
@OneToMany(mappedBy = "myOrder", cascade = CascadeType.All)
private List<Products> productses;
使用列名錯(cuò)誤試試這個(gè):
@ManyToOne
@JoinColumn(name = "myorder_id")
private MyOrder myOrder;
添加回答
舉報(bào)