JPA入门(二)双向一对多

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;
    }
}

你可能感兴趣的:(jpa)