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. POJ 2054 Color a Tree#贪心(难,好题)

    题目链接 代码借鉴此博:http://www.cnblogs.com/vongang/archive/2011/08/19/2146070.html 其中关于max{c[fa]/t[fa]}贪心原则, ...

  2. 付款前.检查状态.防止重复付款,需要ajax设置为同步,等待ajax返回结果再使用

    $("#surePay").on("touchstart",function(){ var apply_id = $('#apply_id').val(); v ...

  3. rabbitmq(1)-入门

    参考: documentation: https://www.rabbitmq.com/documentation.htmldemo: https://www.rabbitmq.com/getstar ...

  4. HashMap解惑

    HashMap中有一些我们容易忽视的点 1. 关于key的hash和equals public V put(K key, V value) { if (table == EMPTY_TABLE) { ...

  5. CevaEclipse - 常用设置

    1. 往工程里面添加在硬盘上已有的文件 File -> Import.. -> General -> File System From directory Browse... 勾选需 ...

  6. NSURL访问项目中的文件

    最近在研究视频处理,具体为:将一个mp4文件,拖入项目工程中,通过url访问文件. 开始代码如下: NSString *path = [[NSBundle mainBundle]pathForReso ...

  7. Python基础篇-day4

    本节目录: 1.字符编码 2.函数 2.1参数 2.2变量 2.3返回值 2.4递归 2.5 编程范式 2.6 高阶函数 *************************************** ...

  8. jquery源码阅读(1)

    每天坚持阅读一定量的的jquery代码,积少成多!加油加油! jquery-2.2.1的9161~9194行 1 if ( typeof define === "function" ...

  9. android配置文件详解

    <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="ht ...

  10. μCos-ii学习笔记2_任务管理

    二.任务管理 任务管理是ucos-ii操作系统的核心内容.这一章大致就以下流程来介绍和总结任务管理的相关知识. 要实现复杂任务管理,必然要定义众多数据来描述任务状态,为了精简,建立了许多不同的数据结构 ...