双向一对多的ddl语句

同单向多对一,单向一对多表的ddl语句一致

Product

package com.jege.jpa.one2many;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table; /**
* @author JE哥
* @email 1272434821@qq.com
* @description:双向:多个商品属于同一个商品类型
*/
@Entity
@Table(name = "t_product")
public class Product {
@Id
@GeneratedValue
private Long id;
private String name;
// 多对一
// optional=false表示外键type_id不能为空
@ManyToOne(optional = true)
@JoinColumn(name = "type_id")
private ProductType type; public Product() { } public Product(String name, ProductType type) {
this.name = name;
this.type = type;
} public Long getId() {
return id;
} public void setId(Long id) {
this.id = id;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public ProductType getType() {
return type;
} public void setType(ProductType type) {
this.type = type;
} @Override
public String toString() {
return "Product [id=" + id + ", name=" + name + "]";
} }

ProductType

package com.jege.jpa.one2many;

import java.util.HashSet;
import java.util.Set; import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table; /**
* @author JE哥
* @email 1272434821@qq.com
* @description:双向:一个商品类型下面有n个商品
*/
@Entity
@Table(name = "t_product_type")
public class ProductType {
@Id
@GeneratedValue
private Long id;
private String name;
// 一对多:集合Set
@OneToMany(mappedBy = "type", orphanRemoval = true)
private Set<Product> products = new HashSet<Product>(); public Long getId() {
return id;
} public void setId(Long id) {
this.id = id;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public Set<Product> getProducts() {
return products;
} public void setProducts(Set<Product> products) {
this.products = products;
} @Override
public String toString() {
return "ProductType [id=" + id + ", name=" + name + "]";
} }

One2ManyTest

package com.jege.jpa.one2many;

import java.util.Set;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query; import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test; /**
* @author JE哥
* @email 1272434821@qq.com
* @description:双向一对多Test
*/
public class One2ManyTest {
private static EntityManagerFactory entityManagerFactory = null;
private EntityManager entityManager = null; @BeforeClass
public static void setUpBeforeClass() throws Exception {
entityManagerFactory = Persistence.createEntityManagerFactory("com.jege.jpa");
} // 一次性保存1一个商品类型,保存这个商品类型下面的2个商品
// 多对一保存的时候必须先保存一方,否则会出现多余的update语句,从而影响性能
@Before
public void persist() throws Exception {
entityManager = entityManagerFactory.createEntityManager();
entityManager.getTransaction().begin(); ProductType type = new ProductType();
type.setName("商品类型1"); Product product1 = new Product("商品1", type);
Product product2 = new Product("商品2", type); entityManager.persist(type);// 持久化状态 商品类型1
entityManager.persist(product1);// 持久化状态
entityManager.persist(product2);// 持久化状态 entityManager.getTransaction().commit();
System.out.println("++++++++++++++++++++");
} // 级联保存
// 需要先修改ProductType.java类
// @OneToMany(mappedBy = "type",cascade=CascadeType.PERSIST)
@Test
public void persist2() throws Exception {
entityManager = entityManagerFactory.createEntityManager();
entityManager.getTransaction().begin(); ProductType type = new ProductType();
type.setName("商品类型1"); // 建立多方到一方的关系
Product product1 = new Product("商品1", type);
Product product2 = new Product("商品2", type); // 从一方建立到多方的关系
type.getProducts().add(product1);
type.getProducts().add(product2);// 临时状态 entityManager.persist(type);// 持久化状态 entityManager.getTransaction().commit();
} // 级联删除
// 需要先修改ProductType.java类
// @OneToMany(mappedBy = "type",cascade=CascadeType.REMOVE)
@Test
public void remove() throws Exception {
entityManager = entityManagerFactory.createEntityManager();
entityManager.getTransaction().begin(); ProductType type = entityManager.find(ProductType.class, 1L);
entityManager.remove(type); entityManager.getTransaction().commit();
} // 只删除一方,不能删除一方里面的多方
// 需要先修改ProductType.java类
// @OneToMany(mappedBy = "type")
@Test
public void remove2() throws Exception {
entityManager = entityManagerFactory.createEntityManager();
entityManager.getTransaction().begin(); ProductType type = entityManager.find(ProductType.class, 1L);
String jpql = "update Product set type=null where type=?";
Query query = entityManager.createQuery(jpql);
query.setParameter(1, type);
int update = query.executeUpdate();
System.out.println("修改成功多少条:"+update); jpql = "delete from ProductType where id=?";
query = entityManager.createQuery(jpql);
query.setParameter(1, type.getId());
update = query.executeUpdate();
System.out.println("删除成功多少条:"+update); entityManager.getTransaction().commit();
} // 获取多方,然后删除一条多方
@Test
public void remove3() throws Exception {
entityManager = entityManagerFactory.createEntityManager();
entityManager.getTransaction().begin(); Product product = entityManager.find(Product.class, 1L);
entityManager.remove(product); entityManager.getTransaction().commit();
} // 获取一方,通过一方来删除一条多方
//需要先修改ProductType.java类
// @OneToMany(mappedBy = "type", orphanRemoval = true)
@Test
public void remove4() throws Exception {
entityManager = entityManagerFactory.createEntityManager();
entityManager.getTransaction().begin(); Product product = entityManager.find(Product.class, 1L);
ProductType type = entityManager.find(ProductType.class, 1L);
type.getProducts().remove(product); entityManager.getTransaction().commit();
} @Test
public void find() throws Exception {
// 不能通过一方获取多方集合是否为null,来判断是否一方是否有多方的数据,只能通过一方获取多方集合.size()来判断
ProductType type = entityManager.find(ProductType.class, 1L);
System.out.println(type);
Set<Product> products = type.getProducts();
if (products.size() > 0) {
System.out.println("当前商品类型下面有商品的");
} else {
System.out.println("当前商品类型下面没有商品的");
}
} @After
public void tearDown() throws Exception {
if (entityManager != null && entityManager.isOpen())
entityManager.close();
} @AfterClass
public static void tearDownAfterClass() throws Exception {
if (entityManagerFactory != null && entityManagerFactory.isOpen())
entityManagerFactory.close();
}
}

其他关联项目

源码地址

https://github.com/je-ge/jpa

如果觉得我的文章对您有帮助,请打赏支持。您的支持将鼓励我继续创作!谢谢!



JPA 系列教程5-双向一对多的更多相关文章

  1. JPA 系列教程4-单向一对多

    JPA中的@OneToMany @Target({METHOD, FIELD}) @Retention(RUNTIME) public @interface OneToMany { Class tar ...

  2. JPA 系列教程21-JPA2.0-@MapKeyColumn

    @MapKeyColumn 用@JoinColumn注解和@MapKeyColumn处理一对多关系 ddl语句 CREATE TABLE `t_employee` ( `id` bigint(20) ...

  3. JPA 系列教程10-双向一对一关联表

    双向一对一关联表的ddl语句 CREATE TABLE `t_person` ( `id` bigint(20) NOT NULL AUTO_INCREMENT, `name` varchar(255 ...

  4. JPA 系列教程9-双向一对一唯一外键

    双向一对一唯一外键的ddl语句 CREATE TABLE `t_person` ( `id` bigint(20) NOT NULL AUTO_INCREMENT, `name` varchar(25 ...

  5. JPA 系列教程7-双向多对多

    双向多对多的ddl语句 同单向多对多表的ddl语句一致 Student package com.jege.jpa.many2many; import java.util.HashSet; import ...

  6. JPA 系列教程17-继承-独立表-TABLE_PER_CLASS

    PerTable策略 每个具体的类一个表的策略 举例 这种映射策略每个类都会映射成一个单独的表,类的所有属性,包括继承的属性都会映射成表的列. 这种映射策略的缺点是:对多态关系的支持有限,当查询涉及到 ...

  7. JPA 系列教程16-继承-联合子类-JOINED

    联合子类策略 这种情况下子类的字段被映射到各自的表中,这些字段包括父类中的字段,并执行一个join操作来实例化子类. 举例 如果实体类Teacher继承实体类Person,实体类Student也继承自 ...

  8. JPA 系列教程13-复合主键-@EmbeddedId+@Embeddable

    复合主键 指多个主键联合形成一个主键组合 需求产生 比如航线一般是由出发地及目的地确定,如果要确定唯一的航线就可以用出发地和目的地一起来表示 ddl语句 同复合主键-2个@Id和复合主键-2个@Id+ ...

  9. JPA 系列教程12-复合主键-2个@Id+@IdClass

    复合主键 指多个主键联合形成一个主键组合 需求产生 比如航线一般是由出发地及目的地确定,如果要确定唯一的航线就可以用出发地和目的地一起来表示 ddl语句 同复合主键-2个@Id一样 Airline p ...

随机推荐

  1. 面试中有关C++的若干问题

    面试中有关C++的若干问题 By 晴天, 2014.5.16晚 什么是多态?简要说一下C++中的多态的概念. (1)定义:多态是指相同对象收到不同消息或者不同对象收到相同消息产生不同的行为. (2)C ...

  2. Kettle启动及简单操作(1)

    官方Hadoop配置 http://wiki.pentaho.com/display/BAD/Configuring+Pentaho+for+your+Hadoop+Distro+and+Versio ...

  3. Python学习笔记第一天

    Python是一门通用脚本语言,灵活,实用,而不用关心本身的实现逻辑! Python通常在linux下编程,有两种方式!当然,为了使用linux文本编辑,所选模式为 非 交互模式! 交互式:简单,方便 ...

  4. The message filter indicated that the application is busy. (Exception from HRESULT: 0x8001010A (RPC_E_SERVERCALL_RETRYLATER))

    消息筛选器显示应用程序正在使用中. ((错误来自 HRESULT:0x8001010A (RPC_E_SERVERCALL_RETRYLATER)) 在对Word文档进行合并或者其他操作的时候,如果数 ...

  5. 第三次冲刺spring会议(第六次会议)

    [例会时间]2014/5/25 21:15 [例会地点]9#446 [例会形式]轮流发言 [例会主持]马翔 [例会记录]兰梦 小组成员:兰梦 ,马翔,李金吉,赵天,胡佳奇

  6. Openjudge-计算概论(A)-点与正方形的关系

    描述: 有一个正方形,四个角的坐标(x,y)分别是(1,-1),(1,1),(-1,-1),(-1,1),x是横轴,y是纵轴.写一个程序,判断一个给定的点是否在这个正方形内.输入输入坐标x,y输出ye ...

  7. ubuntu下打开chm文件

    CHM文件格式是微软1998年推出的基于HTML文件特性的帮助文件系统,以替代早先的WinHelp帮助系统,它在Windows 98中把CHM类型文件称作“已编译的HTML帮助文件”. chm文件因为 ...

  8. ural 1049. Brave Balloonists(标准分解式,数论)

    1049. Brave Balloonists Time limit: 2.0 secondMemory limit: 64 MB Ten mathematicians are flying on a ...

  9. JQuery 多选按钮checkbox

    JQuery 多选按钮checkbox 在需要全选和选择部分的时候我们就需要多选在这里主要介绍了具体的实现 JQuery $(function () { //全选或全不选 $("#allbo ...

  10. 标准IO库

    IO标准库类型和头文件