Given the following entity (some columns omitted from this long definition for brevity):
@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;
How do I get the set of related products for a given product SKU?
The products_related table looks like this:
I know how to get the answer using SQL but I'm new to JPA so I haven't quite grokked the API and query syntax yet.
It seems to me there are some unnecessary collections defined. Anyway:
@JoinTable(name = "Products_Related", joinColumns = {
@JoinColumn(name = "SKU", referencedColumnName = "SKU")}, inverseJoinColumns = {
@JoinColumn(name = "RelatedSKU", referencedColumnName = "SKU")})
@ManyToMany
private Collection<Products> productsCollection2;
This piece (it is present in your code) should give you the desired products. Just rename it to relatedProducts
, and the respective setter/getter.
Update: You can get the object by:
Product p = entityManager.find(Product.class, yourProductId);
p.getRelatedProducts();
Obtaining the entity manager depends on your setup, and a better place to look for how to obtain it, is a tutorial.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With