9 May 2016

JPA: Composite Primary Key with Foreign Keys



 
Entity for the ProductSales Table:
package com.example.model;

import javax.persistence.*;

@Entity
@IdClass(ProductSalesPK.class)
public class ProductSales {

 @Column(name = "QUANTITY")
 private int quantity_sold;

 @Id
 @ManyToOne
 @JoinColumn(name = "sales_id")
 private Sales sales;

 @Id
 @ManyToOne
 @JoinColumn(name = "product_id")
 private Product product;

 public ProductSales() {
 }

 public ProductSales(Sales sales, Product product, int quantity_sold) {
  this.sales = sales;
  this.product = product;
  this.quantity_sold = quantity_sold;
 }

 public Product getProduct() {
  return product;
 }

 public Sales getSales() {
  return sales;
 }

 public void setProduct(Product product) {
  this.product = product;
 }

 public void setSales(Sales sales) {
  this.sales = sales;
 }

 public int getQuantity_sold() {
  return quantity_sold;
 }

 public void setQuantity_sold(int quantity_sold) {
  this.quantity_sold = quantity_sold;
 }

}
ProductSalesPK Id class:

package com.example.model;

import java.util.Objects;

public class ProductSalesPK {
    private int sales;
    private String product;

 public ProductSalesPK(int sales_id, String product_id) {
  this.sales = sales_id;
  this.product = product_id;
 }

 @Override
 public int hashCode() {
  int hash = 5;
  hash = 83 * hash + this.sales;
  hash = 83 * hash + Objects.hashCode(this.product);
  return hash;
 }

 @Override
 public boolean equals(Object obj) {
  if (obj == null) {
   return false;
  }
  if (getClass() != obj.getClass()) {
   return false;
  }
  final ProductSalesPK other = (ProductSalesPK) obj;
  if (this.sales != other.sales) {
   return false;
  }
  if (!Objects.equals(this.product, other.product)) {
   return false;
  }
  return true;
 } 
 
}