jpa一对多映射案例

本文涉及的产品
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
云数据库 RDS MySQL,集群系列 2核4GB
推荐场景:
搭建个人博客
云数据库 RDS PostgreSQL,集群系列 2核4GB
简介: 订单和订单项就是一对多的关系。一个订单有多个订单项,一个订单项属于某个订单。订单和订单项映射后的表结构如下:订单表结构订单项表结构下面就以订单和订单项为例介绍多对多映射关系的实例开发persistence.xml配置文件 <?xml version="1.0"?><persistence xmlns="http://java.sun.com/xml/

订单和订单项就是一对多的关系。一个订单有多个订单项,一个订单项属于某个订单。

订单和订单项映射后的表结构如下:

订单表结构

订单项表结构

下面就以订单和订单项为例介绍多对多映射关系的实例开发

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&amp;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); } } }
复制代码

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; } }
复制代码

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 " ); } }
相关实践学习
如何在云端创建MySQL数据库
开始实验后,系统会自动创建一台自建MySQL的 源数据库 ECS 实例和一台 目标数据库 RDS。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助 &nbsp; &nbsp; 相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
目录
相关文章
|
SQL XML 存储
Hibernate框架【五】——基本映射——多对多映射
Hibernate框架【五】——基本映射——多对多映射
202 0
|
7月前
|
机器学习/深度学习 SQL Java
JPA - 双向多对多映射
JPA - 双向多对多映射
61 2
|
7月前
|
SQL Java 数据库
JPA - 单向一对多映射
JPA - 单向一对多映射
74 2
|
SQL XML Java
Hibernate框架【四】——基本映射——多对一和一对多映射
Hibernate框架【四】——基本映射——多对一和一对多映射
182 0
|
存储 Java 数据库连接
Hibernte的多对多映射(十二)
Hibernte的多对多映射(十二)
Hibernte的多对多映射(十二)
|
存储 Java 数据库连接
Hibernate的一对多映射的单向关联和双向关联(九)
Hibernate的一对多映射的单向关联和双向关联(九)
137 0
Hibernate的一对多映射的单向关联和双向关联(九)
|
Java 数据库连接 数据库
|
存储 Java 数据库连接
hibernate5(10)注解映射[2]一对多单向关联
<div class="markdown_views"> <p>在上一篇文章里,我们从端方向一端建立关联关系,完成了从文章到作者的关联关系建立,但在实际的博客网站中,用户肯定还需要获取自己所写的文章,这时可以建立用户(一)对文章(多)的单向关联映射。 <br> 先来看我们的一方配置实例</p> <pre class="prettyprint"><code class="lan
1869 0