Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA: join table syntax

Tags:

java

jpa

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.

like image 567
Sajee Avatar asked Nov 06 '22 06:11

Sajee


1 Answers

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.

like image 200
Bozho Avatar answered Nov 11 '22 05:11

Bozho