gpt4 book ai didi

Java JPA如何将一个实体实例与另一个实体的所有实例关联起来?

转载 作者:行者123 更新时间:2023-12-01 16:30:32 25 4
gpt4 key购买 nike

我使用嵌入式 H2 数据库,其中使用 @OneToMany 关系将实体实例(产品)与其他实体(供应商)的多个实例相关联;当我有特定产品的特定供应商时,它很有用。但现在,我想将所有供应商与每一个产品关联起来;我不想在我的供应商表中为每个产品生成不同的供应商记录,而是我只想在我的供应商表中只有 5 条记录(5 个供应商),这些记录与每个产品相关联,这几句话我想实现一些目标像“one to all”一样,是否可以使用JPA注释来做到这一点?

产品实体

@Entity
public class Product {

@Id
private String productCode;

@OneToMany
@JoinColumn(name = "supplier_id", referencedColumnName = "productCode")
private List<Supplier> suppliers;

}

供应商实体

@Entity
public class Supplier {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private Long id;

private String name;
}

最佳答案

单向@OneToMany关联:

@Entity
public class Product {

@Id
// @Column(name = "id") maybe
// @GeneratedValue maybe
private String productCode;

@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true) // according to your need
private List<Supplier> suppliers;

...
}

而且,

@Entity
public class Supplier {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

private String name;

...
}



@ManyToOne 关联:

@Entity
public class Product {

@Id
// @Column(name = "id") maybe
// @GeneratedValue maybe
private String productCode;

...
}

而且,

@Entity
public class Supplier {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

@ManyToOne
@JoinColumn(name = "product_id", foreignKey = @ForeignKey(name = "PRODUCT_ID_FK"))
private Product product;

private String name;

...
}

关于Java JPA如何将一个实体实例与另一个实体的所有实例关联起来?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62050443/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com