ranyeli
9/5/2017 - 4:53 AM

Item entity using JPA annotations to create a Many to one relation with suppliers

Item entity using JPA annotations to create a Many to one relation with suppliers

package com.project.model;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Version;

import com.fasterxml.jackson.annotation.JsonBackReference;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonManagedReference;


@Entity
@Table(name="item")
public class Item {

	@Id
	@GeneratedValue(strategy=GenerationType.AUTO)
	private Long id;
	
	private String description;
	
	@Column(precision=2)
	private double price;
	
	@Column(name="CREATED_DATE")
	private Date createdDate;
	
	@Version
	@Column(name="LAST_UPDATED_TIME")
	private Date updatedTime;
	
	@JsonBackReference
	@ManyToOne(optional=false, fetch=FetchType.LAZY)
	@JoinColumn(name="supplier_id")
	private Supplier supplier;
	
//	@JsonManagedReference
	@JsonIgnore
	@OneToMany(mappedBy="items")
	private List<OrderItem> orderItem = new ArrayList<OrderItem>();

	public List<OrderItem> getOrderItem() {
		return orderItem;
	}

	public void setOrderItem(List<OrderItem> orderItem) {
		this.orderItem = orderItem;
	}

	public String getDescription() {
		return description;
	}

	public void setDescription(String description) {
		this.description = description;
	}

	public double getPrice() {
		return price;
	}

	public void setPrice(double price) {
		this.price = price;
	}

//	@JsonIgnore to ignore this on the json result and avoid recursion
	
	// instead of returning the whole supplier object we return only the id to avoid recursion
	public Long getSupplier() {
		return supplier.getId();
	}

	public void setSupplier(Supplier supplier) {
		this.supplier = supplier;
	}

	public Date getUpdatedTime() {
		return updatedTime;
	}
	
	public Date getCreatedDate() {
		return createdDate;
	}

	public Long getId() {
		return id;
	}
	
}