JPA 系列教程3-单向多对一
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();
}
}
其他关联项目
- JPA 系列教程2-单表操作
http://blog.csdn.net/je_ge/article/details/53493352
源码地址
如果觉得我的文章对您有帮助,请打赏支持。您的支持将鼓励我继续创作!谢谢!
JPA 系列教程3-单向多对一的更多相关文章
- JPA 系列教程7-双向多对多
双向多对多的ddl语句 同单向多对多表的ddl语句一致 Student package com.jege.jpa.many2many; import java.util.HashSet; import ...
- JPA 系列教程6-单向多对多
JPA中的@ManyToMany @ManyToMany注释表示模型类是多对多关系的一端. @JoinTable 描述了多对多关系的数据表关系. name 属性指定中间表名称 joinColumns ...
- JPA 系列教程4-单向一对多
JPA中的@OneToMany @Target({METHOD, FIELD}) @Retention(RUNTIME) public @interface OneToMany { Class tar ...
- JPA 系列教程5-双向一对多
双向一对多的ddl语句 同单向多对一,单向一对多表的ddl语句一致 Product package com.jege.jpa.one2many; import javax.persistence.En ...
- JPA 系列教程21-JPA2.0-@MapKeyColumn
@MapKeyColumn 用@JoinColumn注解和@MapKeyColumn处理一对多关系 ddl语句 CREATE TABLE `t_employee` ( `id` bigint(20) ...
- JPA 系列教程17-继承-独立表-TABLE_PER_CLASS
PerTable策略 每个具体的类一个表的策略 举例 这种映射策略每个类都会映射成一个单独的表,类的所有属性,包括继承的属性都会映射成表的列. 这种映射策略的缺点是:对多态关系的支持有限,当查询涉及到 ...
- JPA 系列教程16-继承-联合子类-JOINED
联合子类策略 这种情况下子类的字段被映射到各自的表中,这些字段包括父类中的字段,并执行一个join操作来实例化子类. 举例 如果实体类Teacher继承实体类Person,实体类Student也继承自 ...
- JPA 系列教程13-复合主键-@EmbeddedId+@Embeddable
复合主键 指多个主键联合形成一个主键组合 需求产生 比如航线一般是由出发地及目的地确定,如果要确定唯一的航线就可以用出发地和目的地一起来表示 ddl语句 同复合主键-2个@Id和复合主键-2个@Id+ ...
- JPA 系列教程12-复合主键-2个@Id+@IdClass
复合主键 指多个主键联合形成一个主键组合 需求产生 比如航线一般是由出发地及目的地确定,如果要确定唯一的航线就可以用出发地和目的地一起来表示 ddl语句 同复合主键-2个@Id一样 Airline p ...
随机推荐
- 屏幕居中(DIV/CSS) 的几种方法(转)
1.利用table特性,在width and height all set 100%的时候,可以把容器嵌套在td内形成绝对居中,此时的被嵌套容器可为绝对或者相对大小.(非标准)注意不能加声明! 如是在 ...
- Java 4
1.继承的问题 子类是父类的一个扩展,子类可以利用父类的属性与行为,这种情况子类会破坏父类的封装 为了保持父类良好的封装性,设计父类有以下规则: 如果要把某类设计为最终类则需要添加final修饰符,或 ...
- C# 语言规范_版本5.0 (第3章 基本概念)
1. 基本概念 1.1 应用程序启动 具有入口点 (entry point) 的程序集称为应用程序 (application).应用程序运行时,将创建新的应用程序域 (application doma ...
- vmware虚拟机如何安装ubuntu14.10系统
vmware虚拟机安装ubuntu14.10系统安装步骤如下:
- 获取当前设备的IP地址
头文件: #import <ifaddrs.h> #import <arpa/inet.h> #import <net/if.h> 宏定义: #define IOS ...
- ClassLoader类加载解惑
1.通过类加载器获取路径: String path = Thread.currentThread().getContextClassLoader().getResource("." ...
- mybatis 一点整理
mapper指定对应的接口 <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper ...
- 深入体会__cdecl与__stdcall
在学习C++的过程中时常碰到WINAPI或者CALLBACK这样的调用约定,每每觉得十分迷惑.究竟这些东西有什么用?不用他们又会不会有问题?经过在网上的一番搜寻以及自己动手后,整理成以下的学习笔记.1 ...
- RuntimeError: module compiled against API version 0xa but this version of numpy is 0x9
之前测试安装好Theano之后就去安装Tensorflow,然后再回来执行Theano的测试语句的时候,就出现以下错误了: google了一下,尝试了一下解决方法 import numpy print ...
- 学习multiprocessing(2)
1 代码1: from multiprocessing import Pool import os, time, random def long_time_task(name): print('Run ...