首页 > 代码库 > jpa 双向一对多,多对一关联关系

jpa 双向一对多,多对一关联关系

1.1.  双向一对多

Order.java

package com.morris.entity;
 
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
    @Column(name="order_id",length=32)
    private String orderId;
   
    @Column(name="order_name",length=50)
    private String orderName;
   
    /**
     * OneToMany:一对多的配置
     * mappedBy="order":指定由多的一方的order属性维护关联关系
     *
     */
    @OneToMany(cascade={CascadeType.REFRESH,CascadeType.MERGE,CascadeType.REMOVE,CascadeType.PERSIST},fetch=FetchType.LAZY,mappedBy="order")
    private Set<OrderItem> orderItems;
 
    public Order(String orderId, String orderName, Set<OrderItem> orderItems) {
       super();
       this.orderId = orderId;
       this.orderName = orderName;
       this.orderItems = orderItems;
    }
 
    public Set<OrderItem> getOrderItems() {
       return orderItems;
    }
 
    public void setOrderItems(Set<OrderItem> orderItems) {
       this.orderItems = orderItems;
    }
 
    public Order() {
       super();
       // TODO Auto-generated constructor stub
    }
 
    public Order(String orderId, String orderName) {
       super();
       this.orderId = orderId;
       this.orderName = orderName;
    }
 
    @Override
    public String toString() {
       return "Order [orderId=" + orderId + ", orderName=" + orderName + "]";
    }
 
    public String getOrderId() {
       return orderId;
    }
 
    public void setOrderId(String orderId) {
       this.orderId = orderId;
    }
 
    public String getOrderName() {
       return orderName;
    }
 
    public void setOrderName(String orderName) {
       this.orderName = orderName;
    }
}
 


1.2.  双向多对一

OrderItem.java

package com.morris.entity;
 
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;
import javax.persistence.Table;
 
@Entity
@Table(name="order_item")
public class OrderItem {
    
     @Id
     @GeneratedValue
     @Column(name="order_item_id")
     private Integer orderItemId;
    
     @Column(name="product_name",length=50,nullable=false)
     private String productName;
    
     @Column(name="product_price",nullable=false)
     private Double productPrice;
    
     /**
      * ManyToOne:多对一的配置
      * cascade(级联):all(所有),merge(更新),refresh(查询),persistence(保存),remove(删除)
      * fetch: eager:立即加载  one的一方默认是立即加载
      *            lazy:懒加载    many的一方默认是懒加载
      * optional:是否可选,外键是否允许为空
      *
      * JoinColumn:指定外键名
      *
      */
     @ManyToOne(cascade={CascadeType.MERGE,CascadeType.REFRESH},fetch=FetchType.EAGER,optional=false)
     @JoinColumn(name="order_id")
     private Order order;
 
    
     public OrderItem() {
         super();
         // TODO Auto-generated constructor stub
     }
 
     @Override
     public String toString() {
         return "OrderItem [orderItemId=" + orderItemId + ", productName="
                   + productName + ", productPrice=" + productPrice + ", order="
                   + order + "]";
     }
 
     public Integer getOrderItemId() {
         return orderItemId;
     }
 
     public void setOrderItemId(Integer orderItemId) {
         this.orderItemId = orderItemId;
     }
 
     public String getProductName() {
         return productName;
     }
 
     public void setProductName(String productName) {
         this.productName = productName;
     }
 
     public Double getProductPrice() {
         return productPrice;
     }
 
     public void setProductPrice(Double productPrice) {
         this.productPrice = productPrice;
     }
 
     public Order getOrder() {
         return order;
     }
 
     public void setOrder(Order order) {
         this.order = order;
     }
 
     public OrderItem(String productName,
              Double productPrice) {
         super();
         this.productName = productName;
         this.productPrice = productPrice;
     }
}


 

1.3.  测试

One2ManyTest.java

package com.morris.test;
 
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
 
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
 
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
 
import com.morris.entity.Order;
import com.morris.entity.OrderItem;
 
public class One2ManyTest {
   
    private static EntityManagerFactory factory;
   
    private static EntityManager manager;
 
    @BeforeClass
    public static void setUpBeforeClass() throws Exception {
      
       factory = Persistence.createEntityManagerFactory("jpaDemo");
      
       manager = factory.createEntityManager();
      
       manager.getTransaction().begin();
    }
 
    @Test
    public void test() {
      
       Order order = new Order(UUID.randomUUID().toString(), "体育商品订单");
      
       OrderItem orderItem1 = new OrderItem("足球",120.0);
       OrderItem orderItem2 = new OrderItem("篮球",66.0);
       OrderItem orderItem3 = new OrderItem("羽毛球",118.0);
      
       //一定要设置这个,因为orderItem负责维护关联关系
       orderItem1.setOrder(order);
       orderItem2.setOrder(order);
       orderItem3.setOrder(order);
      
       Set<OrderItem> set = new HashSet<>();
      
       set.add(orderItem1);
       set.add(orderItem2);
       set.add(orderItem3);
      
       order.setOrderItems(set);
      
       manager.persist(order);
      
    }
   
    @AfterClass
    public static void setUpAfterClass() throws Exception {
       manager.getTransaction().commit();
      
       manager.close();
      
       factory.close();
      
    }
}


 

 

jpa 双向一对多,多对一关联关系