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

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



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

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

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

  2. JPA 系列教程6-单向多对多

    JPA中的@ManyToMany @ManyToMany注释表示模型类是多对多关系的一端. @JoinTable 描述了多对多关系的数据表关系. name 属性指定中间表名称 joinColumns ...

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

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

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

    双向一对多的ddl语句 同单向多对一,单向一对多表的ddl语句一致 Product package com.jege.jpa.one2many; import javax.persistence.En ...

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

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

  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. 一、什么是WCF

    注:本文为学习摘抄,原地址:http://www.cnblogs.com/iamlilinfeng/archive/2012/09/25/2700049.html 一.概述 Windows Commu ...

  2. Linux启动kettle及linux和windows中kettle往hdfs中写数据(3)

    在xmanager中的xshell运行进入图形化界面 sh spoon.sh 新建一个job

  3. 与malloc有关的问题

    nefu 1026 申请动态空间存放字符串,将其排序后输出 http://acm.nefu.edu.cn/JudgeOnline/problemShow.php?problem_id=1026 #in ...

  4. JQ N级导航

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...

  5. chapter9_4 非抢占式的多线程

    协同程序与常规的多线程不同之处:协同程序是非抢占式的. 当一个协同程序运行时,是无法从外部停止它的.只有当协同程序显式地调用yield时,它才会停止. 当不存在抢先时,编程会变得简单很多,无须为同步的 ...

  6. POJ 2676 Sudoku(深搜)

    Sudoku Time Limit : 4000/2000ms (Java/Other)   Memory Limit : 131072/65536K (Java/Other) Total Submi ...

  7. DataTable和DataSet有什么区别

    DataTable和DataSet有什么区别 DataSet:数据集.一般包含多个DataTable,用的时候,dataset["表名"]得到DataTable   DataTab ...

  8. [ 订单查询 ] 性能 高并发 : 分表 与 用户id%1024 存放表

    逻辑剥离, 保留核心部分 下单 { 核心功能 -- 买家查看订单, 卖家查看收到订单, 修改价格 5个表 附属功能 -- 库存量, 发短信, 给卖家发通知, 订单统计, 销售额统计 } 下单时 一个数 ...

  9. 慎用#define

    #define INT_MAX     2147483647 INT_MAX+1 就会变成负数 long long r; r > INT_MAX+1 就会出错,应该写成 r > 21474 ...

  10. mongoDB7--游标

    之前我们学习了"增删改查"四中语法和查询表达式的深入学习,我们已经掌握了一定的操作mongodb数据的能力,那么接下来我们就要考虑我们的操作的效率问题了.(1)游标介绍如果我们查询 ...