JPA入門(二)双方向一対多

3010 ワード


package org.jzkangta.onetomany;

import java.util.HashSet;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;

@Entity
@Table(name="orders") //        
public class Order {

	@Id
	private int orderId;
	
	@Column(nullable=false)
	private Float allPrice = 0f;
	
	@OneToMany(cascade=CascadeType.ALL,fetch=FetchType.LAZY,mappedBy="order") //cascade      fetch    ,          mappedBy            ,order        
	private Set<OrderItem> items = new HashSet<OrderItem>();
	
	public int getOrderId() {
    	return orderId;
    }
	public void setOrderId( int orderId ) {
    	this.orderId = orderId;
    }
	public Float getAllPrice() {
    	return allPrice;
    }
	public void setAllPrice( Float allPrice ) {
    	this.allPrice = allPrice;
    }
	public Set<OrderItem> getItems() {
    	return items;
    }
	public void setItems( Set<OrderItem> items ) {
    	this.items = items;
    }
}


package org.jzkangta.onetomany;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;

/**
 *           ,              
 * @author Administrator
 *
 */
@Entity
public class OrderItem {

	@Id
	@GeneratedValue
	private int id;
	
	@Column(length=40,nullable=false)
	private String name;
	
	@Column(nullable=false)
	private Float price = 0f;
	
	@ManyToOne(cascade={CascadeType.MERGE,CascadeType.REFRESH},fetch=FetchType.EAGER,optional=false)//cascade   ALL,fetch=FetchType.EAGER   ,optional=true  order   null
	@JoinColumn(name="order_id")//       
	private Order order;
	
	public int getId() {
    	return id;
    }
	public void setId( int id ) {
    	this.id = id;
    }
	public String getName() {
    	return name;
    }
	public void setName( String name ) {
    	this.name = name;
    }
	public Float getPrice() {
    	return price;
    }
	public void setPrice( Float price ) {
    	this.price = price;
    }
	public Order getOrder() {
    	return order;
    }
	public void setOrder( Order order ) {
    	this.order = order;
    }
}