JPAのJPAにおける一対の多双方向関連

5650 ワード

JPA開発環境を構築する場合は、JPAの最初のブログからご覧ください.
JPA仕様では、双方向の一対多または多対一の関係において、複数の一方が関係維持端であり、関係維持端は外部キー記録の更新を担当し、関係被維持端は外部記録を更新する権利がないと規定されている.
 
ここでは、受注と受注項目を例に挙げます.1つの受注には複数の受注項目があり、1つの受注項目は1つの受注にのみ帰属します.
1、新規Orderクラス、作成コードは以下の通り
package cn.sunft.bean;

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 {
	private String orderid;
	private Float amount = 0f;
	//         
	private Set items = new HashSet<>();

	@Id
	@Column(length=12)
	public String getOrderid() {
		return orderid;
	}

	public void setOrderid(String orderid) {
		this.orderid = orderid;
	}

	@Column(nullable=false)
	public Float getAmount() {
		return amount;
	}

	public void setAmount(Float amount) {
		this.amount = amount;
	}

	//    ,  Order       OrderItem,           
	//   fetch              EntityManager      
	//      :       Many ,       ;   One ,  
	//    
	//mappedBy  :           ,              
	//         ,JPA               ;    OrderItem
	//  order      
	@OneToMany(cascade=
		{CascadeType.PERSIST, CascadeType.REMOVE, CascadeType.REFRESH, 
			CascadeType.MERGE, CascadeType.DETACH}, 
			fetch = FetchType.LAZY, mappedBy="order")
	public Set getItems() {
		return items;
	}

	public void setItems(Set items) {
		this.items = items;
	}
	
	/**
	 *      
	 * @param orderItem
	 */
	public void addOrderItem(OrderItem orderItem){
		orderItem.setOrder(this);//    
		this.items.add(orderItem);
	}
	
}

2、OrderItemクラスを新規作成し、以下のコードを作成する.
package cn.sunft.bean;

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

/**
 *    
 */
@Entity
public class OrderItem {

	private Integer id;
	private String productName;
	private Float sellPrice = 0f;
	private Order order;//       

	@Id
	@GeneratedValue
	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	@Column(length=40, nullable=false)
	public String getProductName() {
		return productName;
	}

	public void setProductName(String productName) {
		this.productName = productName;
	}

	@Column(nullable=false)
	public Float getSellPrice() {
		return sellPrice;
	}

	public void setSellPrice(Float sellPrice) {
		this.sellPrice = sellPrice;
	}

	//           
	//optional=true:  order       null
	//optional=false:  order        ,      。
	@ManyToOne(cascade={CascadeType.MERGE, CascadeType.REFRESH}, optional=false)
	@JoinColumn(name="order_id")//         
	public Order getOrder() {
		return order;
	}

	public void setOrder(Order order) {
		this.order = order;
	}

}

3、テストクラスを作成してテストする
package junit.test;

import java.util.Set;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import org.junit.Test;

import cn.sunft.bean.Order;
import cn.sunft.bean.OrderItem;
import cn.sunft.bean.Person;

public class OneToManyTest {
	
	@Test
	public void save(){
		EntityManagerFactory factory 
			= Persistence.createEntityManagerFactory("sunft_first");
		EntityManager em = factory.createEntityManager();
		em.getTransaction().begin();
		Order order = new Order();
		order.setAmount(34f);
		order.setOrderid("999");
		
		OrderItem orderItem1 = new OrderItem();
		orderItem1.setProductName("  ");
		orderItem1.setSellPrice(90f);
		OrderItem orderItem2 = new OrderItem();
		orderItem2.setProductName("  ");
		orderItem2.setSellPrice(90f);
		
		order.addOrderItem(orderItem1);//     
		order.addOrderItem(orderItem2);//     
		
		//     ,            
		em.persist(order);
		em.getTransaction().commit();
		em.close();
		factory.close();
	}
	
	@Test
	public void get(){
		EntityManagerFactory factory 
		= Persistence.createEntityManagerFactory("sunft_first");
		EntityManager em = factory.createEntityManager();
		em.getTransaction().begin();
		Order order = em.find(Order.class, "999");
		System.out.println("order:" + order);
		Set settings = order.getItems();
		System.out.println("settings:" + settings);
		em.getTransaction().commit();
		em.close();
		factory.close();
	}
	
	/**
	 *       
	 */
	@Test
	public void update(){
		EntityManagerFactory factory 
			= Persistence.createEntityManagerFactory("sunft_first");
		EntityManager em = factory.createEntityManager();
		em.getTransaction().begin();
		Order order = em.find(Order.class, "999");
		order.setAmount(40f);
		System.out.println("order:" + order);
		Set settings = order.getItems();
		for(OrderItem item : settings){
			item.setSellPrice(80f);
		}
		em.merge(order);
		em.getTransaction().commit();
		em.close();
		factory.close();
		
	}
	
	/**
	 *       
	 */
	@Test
	public void delete() {
		EntityManagerFactory factory 
			= Persistence.createEntityManagerFactory("sunft_first");
		EntityManager em = factory.createEntityManager();
		em.getTransaction().begin();//    
		Order order = em.find(Order.class, "999");
		em.remove(order);
		em.getTransaction().commit();
		em.close();
		factory.close();
	}

}