gpt4 book ai didi

java - JPA:连接表语法

转载 作者:搜寻专家 更新时间:2023-10-31 20:30:57 25 4
gpt4 key购买 nike

给定以下实体(为简洁起见,此长定义中省略了一些列):

@Table(name = "Products")
public class Products implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Basic(optional = false)
@Column(name = "SKU")
private String sku;
@Basic(optional = false)
@Column(name = "ProductName")
private String productName;

private boolean allowPreOrder;
@ManyToMany(mappedBy = "productsCollection")
private Collection<Categories> categoriesCollection;
@JoinTable(name = "Products_CrossSell", joinColumns = {
@JoinColumn(name = "SKU", referencedColumnName = "SKU")}, inverseJoinColumns = {
@JoinColumn(name = "CrossSKU", referencedColumnName = "SKU")})
@ManyToMany
private Collection<Products> productsCollection;
@ManyToMany(mappedBy = "productsCollection")
private Collection<Products> productsCollection1;
@JoinTable(name = "Products_Related", joinColumns = {
@JoinColumn(name = "SKU", referencedColumnName = "SKU")}, inverseJoinColumns = {
@JoinColumn(name = "RelatedSKU", referencedColumnName = "SKU")})
@ManyToMany
private Collection<Products> productsCollection2;
@ManyToMany(mappedBy = "productsCollection2")
private Collection<Products> productsCollection3;

如何获取给定产品 SKU 的一组相关产品?

products_related 表如下所示:

alt text

我知道如何使用 SQL 获得答案,但我是 JPA 的新手,所以我还没有完全理解 API 和查询语法。

最佳答案

在我看来,定义了一些不必要的集合。无论如何:

@JoinTable(name = "Products_Related", joinColumns = {
@JoinColumn(name = "SKU", referencedColumnName = "SKU")}, inverseJoinColumns = {
@JoinColumn(name = "RelatedSKU", referencedColumnName = "SKU")})
@ManyToMany
private Collection<Products> productsCollection2;

这部分(它存在于您的代码中)应该会为您提供所需的产品。只需将其重命名为 relatedProducts,以及相应的 setter/getter。

更新:您可以通过以下方式获取对象:

Product p = entityManager.find(Product.class, yourProductId);
p.getRelatedProducts();

获取实体管理器取决于您的设置,一个更好的查找如何获取它的地方是教程。

关于java - JPA:连接表语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4180905/

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