订单和订单项就是一对多的关系。一个订单有多个订单项,一个订单项属于某个订单。
订单和订单项映射后的表结构如下:
订单表结构
订单项表结构
下面就以订单和订单项为例介绍多对多映射关系的实例开发
persistence.xml配置文件
<?
xml version
=
"
1.0
"
?>
< persistence xmlns = " http://java.sun.com/xml/ns/persistence " xmlns:xsi = " http://www.w3.org/2001/XMLSchema-instance "
xsi:schemaLocation = " http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd " version = " 1.0 " >
<!-- 事务类型:本地事务(仅针对一个数据库)和全局事务(针对多个数据库);RESOURCE_LOCAL: 本地事务 -->
< persistence - unit name = " ljq " transaction - type = " RESOURCE_LOCAL " >
< properties >
< property name = " hibernate.dialect " value = " org.hibernate.dialect.MySQL5Dialect " />
< property name = " hibernate.connection.driver_class " value = " org.gjt.mm.mysql.Driver " />
< property name = " hibernate.connection.username " value = " root " />
< property name = " hibernate.connection.password " value = " mysql " />
< property name = " hibernate.connection.url " value = " jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8 " />
< property name = " hibernate.hbm2ddl.auto " value = " update " />
</ properties >
</ persistence - unit >
</ persistence >
< persistence xmlns = " http://java.sun.com/xml/ns/persistence " xmlns:xsi = " http://www.w3.org/2001/XMLSchema-instance "
xsi:schemaLocation = " http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd " version = " 1.0 " >
<!-- 事务类型:本地事务(仅针对一个数据库)和全局事务(针对多个数据库);RESOURCE_LOCAL: 本地事务 -->
< persistence - unit name = " ljq " transaction - type = " RESOURCE_LOCAL " >
< properties >
< property name = " hibernate.dialect " value = " org.hibernate.dialect.MySQL5Dialect " />
< property name = " hibernate.connection.driver_class " value = " org.gjt.mm.mysql.Driver " />
< property name = " hibernate.connection.username " value = " root " />
< property name = " hibernate.connection.password " value = " mysql " />
< property name = " hibernate.connection.url " value = " jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8 " />
< property name = " hibernate.hbm2ddl.auto " value = " update " />
</ properties >
</ persistence - unit >
</ persistence >
Order订单类
package
com.ljq.entity;
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;
/**
* one端
*
* 碰到many为末端的加载就是延迟加载,若one为末端则为立即加载,除了one-to-one。
*
* @author jiqinlin
*
*/
@Entity
@Table(name = " tb_order " )
@SuppressWarnings( " serial " )
public class Order implements java.io.Serializable {
// String类型不能用uuid,需要人为指定
@Id
@Column(length = 12 )
private String orderid;
@Column(nullable = false )
private Float amount = 0f;
// @OneToMany(cascade={CascadeType.PERSIST,CascadeType.MERGE,CascadeType.REMOVE})
// mappedBy="order": 指明Order类为双向关系维护端,负责外键的更新
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = " order " )
private Set < OrderItem > items = new HashSet < OrderItem > ();
public Order() {
super ();
}
public Float getAmount() {
return amount;
}
public void setAmount(Float amount) {
this .amount = amount;
}
public String getOrderid() {
return orderid;
}
public void setOrderid(String orderid) {
this .orderid = orderid;
}
public Set < OrderItem > getItems() {
return items;
}
public void setItems(Set < OrderItem > items) {
this .items = items;
}
/**
* 添加订单项
*
* @param student
*/
public void addOrderItem(OrderItem item) {
if ( ! this .items.contains(item)) {
this .items.add(item);
item.setOrder( this );
}
}
/**
* 删除订单项
*
* @param student
*/
public void removeOrderItem(OrderItem item) {
if ( this .items.contains(item)) {
item.setOrder( null );
this .items.remove(item);
}
}
}
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;
/**
* one端
*
* 碰到many为末端的加载就是延迟加载,若one为末端则为立即加载,除了one-to-one。
*
* @author jiqinlin
*
*/
@Entity
@Table(name = " tb_order " )
@SuppressWarnings( " serial " )
public class Order implements java.io.Serializable {
// String类型不能用uuid,需要人为指定
@Id
@Column(length = 12 )
private String orderid;
@Column(nullable = false )
private Float amount = 0f;
// @OneToMany(cascade={CascadeType.PERSIST,CascadeType.MERGE,CascadeType.REMOVE})
// mappedBy="order": 指明Order类为双向关系维护端,负责外键的更新
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = " order " )
private Set < OrderItem > items = new HashSet < OrderItem > ();
public Order() {
super ();
}
public Float getAmount() {
return amount;
}
public void setAmount(Float amount) {
this .amount = amount;
}
public String getOrderid() {
return orderid;
}
public void setOrderid(String orderid) {
this .orderid = orderid;
}
public Set < OrderItem > getItems() {
return items;
}
public void setItems(Set < OrderItem > items) {
this .items = items;
}
/**
* 添加订单项
*
* @param student
*/
public void addOrderItem(OrderItem item) {
if ( ! this .items.contains(item)) {
this .items.add(item);
item.setOrder( this );
}
}
/**
* 删除订单项
*
* @param student
*/
public void removeOrderItem(OrderItem item) {
if ( this .items.contains(item)) {
item.setOrder( null );
this .items.remove(item);
}
}
}
OrderItem订单项类
package
com.ljq.entity;
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;
import javax.persistence.Table;
/**
* many端
*
* 在one-to-many双向关联中,多的一方为关系维护端,关系维护端负责外键记录的更新
* 关系被维护端是没有权力更新外键记录的
*
* @author jiqinlin
*
*/
@Entity
@Table(name = " tb_orderitem " )
@SuppressWarnings( " serial " )
public class OrderItem implements java.io.Serializable {
@Id
@GeneratedValue
private Integer id;
@Column(length = 40 , nullable = false )
private String productName;
@Column(nullable = false )
private Float sellPrice = 0f;
// optional=true:可选,表示此对象可以没有,可以为null;false表示必须存在
@ManyToOne(cascade = { CascadeType.REFRESH, CascadeType.MERGE }, optional = true )
@JoinColumn(name = " order_id " )
private Order order;
public OrderItem() {
super ();
}
public OrderItem(String productName, Float sellPrice) {
super ();
this .productName = productName;
this .sellPrice = sellPrice;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this .id = id;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this .productName = productName;
}
public Float getSellPrice() {
return sellPrice;
}
public void setSellPrice(Float sellPrice) {
this .sellPrice = sellPrice;
}
public Order getOrder() {
return order;
}
public void setOrder(Order order) {
this .order = order;
}
}
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;
import javax.persistence.Table;
/**
* many端
*
* 在one-to-many双向关联中,多的一方为关系维护端,关系维护端负责外键记录的更新
* 关系被维护端是没有权力更新外键记录的
*
* @author jiqinlin
*
*/
@Entity
@Table(name = " tb_orderitem " )
@SuppressWarnings( " serial " )
public class OrderItem implements java.io.Serializable {
@Id
@GeneratedValue
private Integer id;
@Column(length = 40 , nullable = false )
private String productName;
@Column(nullable = false )
private Float sellPrice = 0f;
// optional=true:可选,表示此对象可以没有,可以为null;false表示必须存在
@ManyToOne(cascade = { CascadeType.REFRESH, CascadeType.MERGE }, optional = true )
@JoinColumn(name = " order_id " )
private Order order;
public OrderItem() {
super ();
}
public OrderItem(String productName, Float sellPrice) {
super ();
this .productName = productName;
this .sellPrice = sellPrice;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this .id = id;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this .productName = productName;
}
public Float getSellPrice() {
return sellPrice;
}
public void setSellPrice(Float sellPrice) {
this .sellPrice = sellPrice;
}
public Order getOrder() {
return order;
}
public void setOrder(Order order) {
this .order = order;
}
}
OrderTest测试类
package
com.ljq.test;
import java.io.Serializable;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import org.junit.Test;
import com.ljq.entity.Order;
import com.ljq.entity.OrderItem;
import com.sun.org.apache.xpath.internal.operations.Or;
public class OrderTest {
/**
* 添加订单Order时同时添加两个订单项OrderItem,因为订单Order为双向关系维护者,起着主导作用
*/
@Test
public void save() {
EntityManagerFactory factory = Persistence.createEntityManagerFactory( " ljq " );
EntityManager em = factory.createEntityManager();
em.getTransaction().begin();
Order order = new Order();
order.setAmount(34f);
// UUID.randomUUID().toString()
order.setOrderid( " xxxx " );
order.addOrderItem( new OrderItem( " 足球 " ,20f));
order.addOrderItem( new OrderItem( " 篮球 " ,25f));
em.persist(order);
em.getTransaction().commit();
em.close();
factory.close();
}
/**
* 删除Order对象时,会自动删除OrderItem对象(即:父对象删除时子对象跟着删除)
*/
@Test
public void detele1(){
EntityManagerFactory factory = Persistence.createEntityManagerFactory( " ljq " );
EntityManager em = factory.createEntityManager();
em.getTransaction().begin();
Order order = em.getReference(Order. class , " xxxx " );
em.remove(order);
em.getTransaction().commit();
em.close();
factory.close();
}
/**
* 删除子对象时,父对象没影响
*/
@Test
public void detele2(){
EntityManagerFactory factory = Persistence.createEntityManagerFactory( " ljq " );
EntityManager em = factory.createEntityManager();
em.getTransaction().begin();
OrderItem item = em.getReference(OrderItem. class , (Serializable) 3 );
em.remove(item);
em.getTransaction().commit();
em.close();
factory.close();
}
// 运行结果为:
// orderid:xxxx, amount:34.0
// productName:足球price:20.0
// productName:篮球price:25.0
// ===============
@Test
public void find1(){
EntityManagerFactory factory = Persistence.createEntityManagerFactory( " ljq " );
EntityManager em = factory.createEntityManager();
em.getTransaction().begin();
List < Order > orders = em.createQuery( " select o from Order o " ).getResultList();
for (Order order:orders){
System.out.println( " orderid: " + order.getOrderid() + " , " + " amount: " + order.getAmount());
Set < OrderItem > orderItems = order.getItems();
for (OrderItem item:orderItems){
System.out.println( " productName: " + item.getProductName() + " price: " + item.getSellPrice());
}
System.out.println( " =============== " );
}
em.close();
factory.close();
}
// 运行结果为
// productName:足球price:20.0
// orderid:xxxx, amount:34.0
// ============
// productName:篮球price:25.0
// orderid:xxxx, amount:34.0
// ============
@Test
public void find2(){
EntityManagerFactory factory = Persistence.createEntityManagerFactory( " ljq " );
EntityManager em = factory.createEntityManager();
em.getTransaction().begin();
List < OrderItem > items = em.createQuery( " select o from OrderItem o " ).getResultList();
for (OrderItem item:items){
System.out.println( " productName: " + item.getProductName() + " price: " + item.getSellPrice());
Order order = item.getOrder();
System.out.println( " orderid: " + order.getOrderid() + " , " + " amount: " + order.getAmount());
System.out.println( " ============ " );
}
em.close();
factory.close();
}
/**
* 测试jpa环境是否搭建成功
*
*/
@Test
public void test() {
Persistence.createEntityManagerFactory( " ljq " );
}
}
import java.io.Serializable;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import org.junit.Test;
import com.ljq.entity.Order;
import com.ljq.entity.OrderItem;
import com.sun.org.apache.xpath.internal.operations.Or;
public class OrderTest {
/**
* 添加订单Order时同时添加两个订单项OrderItem,因为订单Order为双向关系维护者,起着主导作用
*/
@Test
public void save() {
EntityManagerFactory factory = Persistence.createEntityManagerFactory( " ljq " );
EntityManager em = factory.createEntityManager();
em.getTransaction().begin();
Order order = new Order();
order.setAmount(34f);
// UUID.randomUUID().toString()
order.setOrderid( " xxxx " );
order.addOrderItem( new OrderItem( " 足球 " ,20f));
order.addOrderItem( new OrderItem( " 篮球 " ,25f));
em.persist(order);
em.getTransaction().commit();
em.close();
factory.close();
}
/**
* 删除Order对象时,会自动删除OrderItem对象(即:父对象删除时子对象跟着删除)
*/
@Test
public void detele1(){
EntityManagerFactory factory = Persistence.createEntityManagerFactory( " ljq " );
EntityManager em = factory.createEntityManager();
em.getTransaction().begin();
Order order = em.getReference(Order. class , " xxxx " );
em.remove(order);
em.getTransaction().commit();
em.close();
factory.close();
}
/**
* 删除子对象时,父对象没影响
*/
@Test
public void detele2(){
EntityManagerFactory factory = Persistence.createEntityManagerFactory( " ljq " );
EntityManager em = factory.createEntityManager();
em.getTransaction().begin();
OrderItem item = em.getReference(OrderItem. class , (Serializable) 3 );
em.remove(item);
em.getTransaction().commit();
em.close();
factory.close();
}
// 运行结果为:
// orderid:xxxx, amount:34.0
// productName:足球price:20.0
// productName:篮球price:25.0
// ===============
@Test
public void find1(){
EntityManagerFactory factory = Persistence.createEntityManagerFactory( " ljq " );
EntityManager em = factory.createEntityManager();
em.getTransaction().begin();
List < Order > orders = em.createQuery( " select o from Order o " ).getResultList();
for (Order order:orders){
System.out.println( " orderid: " + order.getOrderid() + " , " + " amount: " + order.getAmount());
Set < OrderItem > orderItems = order.getItems();
for (OrderItem item:orderItems){
System.out.println( " productName: " + item.getProductName() + " price: " + item.getSellPrice());
}
System.out.println( " =============== " );
}
em.close();
factory.close();
}
// 运行结果为
// productName:足球price:20.0
// orderid:xxxx, amount:34.0
// ============
// productName:篮球price:25.0
// orderid:xxxx, amount:34.0
// ============
@Test
public void find2(){
EntityManagerFactory factory = Persistence.createEntityManagerFactory( " ljq " );
EntityManager em = factory.createEntityManager();
em.getTransaction().begin();
List < OrderItem > items = em.createQuery( " select o from OrderItem o " ).getResultList();
for (OrderItem item:items){
System.out.println( " productName: " + item.getProductName() + " price: " + item.getSellPrice());
Order order = item.getOrder();
System.out.println( " orderid: " + order.getOrderid() + " , " + " amount: " + order.getAmount());
System.out.println( " ============ " );
}
em.close();
factory.close();
}
/**
* 测试jpa环境是否搭建成功
*
*/
@Test
public void test() {
Persistence.createEntityManagerFactory( " ljq " );
}
}