Sajee
Sajee

Reputation: 4457

JPA: join table syntax

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:

alt text

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.

Upvotes: 5

Views: 4954

Answers (1)

Bozho
Bozho

Reputation: 597324

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.

Upvotes: 2

Related Questions