zoukankan      html  css  js  c++  java
  • JPA 系列教程5-双向一对多

    双向一对多的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

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

  • 相关阅读:
    那些容易忽略的事4-(正则表达式反向引用 )
    那些容易忽略的事3-(变量提升和函数提升)
    那些容易忽略的事(2)
    那些容易忽略的事(1) -变量与运算符+
    call()与apply()传参需要注意的一点
    CSS凹型导航按钮
    动态的99乘法表
    js中的for-of循环遍历数组
    交换2个变量的值
    gl.disableVertexArray P77 关闭location指定的attribute变量
  • 原文地址:https://www.cnblogs.com/je-ge/p/6160942.html
Copyright © 2011-2022 走看看