双向一对多的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. wamp,phpserver,xampp环境冲突

    这几天在使用laravel5.2时 执行:php artisan migrate [PDOException] could not find driver 分析可能是以下情况造成 1 php.ini配 ...

  2. Linq使用方法

    int pollid = poll.Where(f => f.PollID < CurrentId).OrderByDescending(o => o.PollID).FirstOr ...

  3. 关于R语言的一些编程经验

    一个晚上写出一个能用的程序…… 来说说遇见的问题吧 zqw<-read.table(file = "c:/data/zqw.txt") zqw<-data.frame( ...

  4. Graph Algorithm

    1.定义 A graph consists of a set of vertices V and a set of edges E. Each edge is a pair (v, w), where ...

  5. MySQL(1) - 基础

    参考资料: http://www.jianshu.com/p/91e3af27743f 一.MySQL介绍以及安装 1.1 MySQL介绍 MariaDB数据库管理系统是MySQL的一个分支,主要由开 ...

  6. thrift安装笔记

    Thrift源于大名鼎鼎的facebook之手,在2007年facebook提交Apache基金会将Thrift作为一个开源项目,对于当时 的facebook来说创造thrift是为了解决facebo ...

  7. NOIP2012-普及组复赛-第一题-质因数分解

    题目描述 Description 已知正整数n是两个不同的质数的乘积,试求出两者中较大的那个质数.  输入输出格式 Input/output 输入格式:输入只有一行,包含一个正整数n.输出格式:输出只 ...

  8. padding当高度用时出现的问题

    <div class="wrap"> <div class="sudoku"> <div class="sdk-wrap ...

  9. 第二题 已知有十六支男子足球队参加2008 北京奥运会。写一个程序,把这16 支球队随机分为4 个组。采用List集合和随机数     2008 北京奥运会男足参赛国家:  科特迪瓦,阿根廷,澳大利亚,塞尔维亚,荷兰,尼日利亚、日本,美国,中国,新西 兰,巴西,比利时,韩国,喀麦隆,洪都拉斯,意大利

    import java.util.ArrayList; import java.util.List; import java.util.Random; public class List1 { pub ...

  10. 21.编写一个Java应用程序,该程序包括3个类:Monkey类、People类和主类 E。要求: (1) Monkey类中有个构造方法:Monkey (String s),并且有个public void speak() 方法,在speak方法中输出“咿咿呀呀......”的信息。 (2)People类是Monkey类的子类,在People类中重写方法speak(),在speak方法 中输出“小样

    //Monkey类 package d922; public class Monkey { Monkey() { } Monkey (String s) { System.out.println(s) ...