给定以下实体(为了简洁,在这个长定义中省略了一些列):
@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表如下所示:
我知道如何使用SQL获得答案,但我是JPA的新手,所以我还没有完全了解API和查询语法。
答案 0 :(得分:2)
在我看来,定义了一些不必要的集合。无论如何:
@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();
获取实体管理器取决于您的设置,并且是一个更好的地方来查找如何获取它,是一个教程。