双向一对多的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. QQ头像一键添加校徽

    简书链接地址:http://www.jianshu.com/p/dcb2cbd07e4d 项目展示链接地址:www.zhaozhengyu.cn/SchoolImage/index.html

  2. Objetive-C +load方法研究

    load方法的执行时机           Objetive-C 的runtime会在一个类的所有方法加载到内存中时调用这个类的+load() 方法,因为每个类的方法只是加载一次,所以每个+load( ...

  3. Storm 分配逻辑

    ps:都是学习的别人的博客,只是做了个整理所有就写成了原创,其实都是人家的东西 当一个topology在storm cluster中运行时,它的并发主要跟3个逻辑对象相关:worker,executo ...

  4. MC- 挂单STOP交易

    using System; using System.Drawing; using System.Linq; using PowerLanguage.Function; using ATCenterP ...

  5. chapter 13_1 算术类的元方法

    假设用table来表示集合,用function去计算集合的交集.并集. 为了保持名称空间的整齐,将这些函数存入一个名为Set的table中. 现在,假设用“+”来计算两个集合的并集,那么就要让所有用于 ...

  6. LINQ的Any() 方法

    Enumerable.Any 方法 确定序列中的任何元素是否存在或满足条件.

  7. 常用 NHibernate.Criterion

    Expression.Where<ScreenView>((v) => v.bizType != 0);

  8. ( ̄▽ ̄") 没钱了

    ( ̄▽ ̄") 没钱了 TimeLimit: 1000ms  MenoryLimit:65536KB 64-bit integer IO format:%lld Problem Descrip ...

  9. Value '0000-00-00' can not be represented as java.sql.Date

    Value '0000-00-00' can not be represented as java.sql.Date 时间 2014-07-30 09:00:50 ITeye-博客 原文  http: ...

  10. HTML-input标签需设置的属性

    <input placeholder="这里输入门店名称" autocomplete="off" id="" name="& ...