JPA 菜鸟教程 3 单向多对一

GitHub

src="//ghbtns.com/github-btn.html?user=je-ge&repo=jpa&type=watch&count=true" scrolling="0" width="110" height="20">

JPA中的@ManyToOne

主要属性
- name(必需): 设定“many”方所包含的“one”方所对应的持久化类的属性名
- column(可选): 设定one方的主键,即持久化类的属性对应的表的外键
- class(可选): 设定one方对应的持久化类的名称,即持久化类属性的类型
- not-null(可选): 如果为true,,表示需要建立相互关联的两个表之间的外键约束
- cascade(可选): 级联操作选项,默认为none

单向多对一(@ManyToOne)关联是最常见的单向关联关系。假设多种商品(Product)可以有一个商品类型(ProductType),只关心商品(Product)实体找到对应的商品类型(ProductType)实体,而无须关心从某个商品类型(ProductType)找到全部商品(Product).

单向多对一表的ddl语句

CREATE TABLE `t_product_type` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

CREATE TABLE `t_product` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  `type_id` bigint(20) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `FK_oyt6r2g6hwbyee5adel4yj59e` (`type_id`),
  CONSTRAINT `FK_oyt6r2g6hwbyee5adel4yj59e` FOREIGN KEY (`type_id`) REFERENCES `t_product_type` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

Product

package com.jege.jpa.many2one;

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.many2one;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

/**
 * @author JE哥
 * @email 1272434821@qq.com
 * @description:单向
 */
@Entity
@Table(name = "t_product_type")
public class ProductType {
  @Id
  @GeneratedValue
  private Long id;
  private String name;

  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;
  }

  @Override
  public String toString() {
    return "ProductType [id=" + id + ", name=" + name + "]";
  }

}

Many2OneTest

package com.jege.jpa.many2one;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

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 Many2OneTest {
  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");

    // 传入type的本质是处理数据库product表的type_id外键
    Product product1 = new Product("产品1", null);
    Product product2 = new Product("产品2", type);

    System.out.println("保存之前:" + type);
    entityManager.persist(type);// JPA会自动把保存后的主键放到当前对象的id里面
    System.out.println("保存之后:" + type);
    entityManager.persist(product1);
    entityManager.persist(product2);
    System.out.println("++++++++++++++++++++");
  }

  // 可以通过多方Product获取一方ProductType是否为null,来判断是否有产品类型
  @Test
  public void find() throws Exception {
    Product product = entityManager.find(Product.class, 2L);
    System.out.println(product);
    ProductType type = product.getType();
    if (type == null) {
      System.out.println("当前产品是没有产品类型的");
    } else {
      System.out.println("当前产品是有产品类型的");
    }
  }

  @After
  public void tearDown() throws Exception {
    entityManager.getTransaction().commit();
    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

如果觉得我的文章或者代码对您有帮助,可以请我喝杯咖啡。
您的支持将鼓励我继续创作!谢谢!
微信打赏
支付宝打赏

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值