jpa 一对多and 多对一
配置:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0"
xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="JPA" transaction-type="RESOURCE_LOCAL">
<!-- 配置用什么orm 产品作为jpa的实现 -->
<!-- 1.实际上配置的是 javax.persistence.spi.PersistenceProvider接口的实现类 2.若只有一个jpa的实现,也可以比配置该节点
-->
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<!-- 添加持久化类 -->
<class>entity.Customer</class>
<class>entity.Order</class> <properties>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql:///jpa" />
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
<property name="javax.persistence.jdbc.user" value="root" />
<property name="javax.persistence.jdbc.password" value="manager123" /> <!-- 配置jpa的实现产品的基本属性,配置hibernate的基本属性 -->
<property name="hibernate.format_sql" value="true" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.hbm2ddl.auto" value="update" />
</properties>
</persistence-unit>
</persistence>
entity customer
package entity; import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set; import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType; import org.eclipse.persistence.jpa.config.Cascade; @Table(name = "customer")
@Entity
public class Customer { private int id;
private String lastName;
private String email;
private int age; private Date birthday;
private Date creatTime; /******** 一对多关系, 一个顾客,有多个订单 ********/
Set<Order> orders = new HashSet<Order>(); @JoinColumn(name = "CUSTOMER_ID") // 用来映射外键列的名称
//cascade={CascadeType.REMOVE} 设置级联删除
//mappedBy="customer" 设置谁来维护关系爱 (在此设置多的 customer维护,及Customer不维护,有order维护)
//!!!使用mappedBy="XX“属性,@JoinColumn(name="XXXX")不用指定(否则会报错)
@OneToMany(fetch=FetchType.EAGER,cascade={CascadeType.REMOVE},mappedBy="customer") // 映射一对多的关系
public Set<Order> getOrders() {
return orders;
} public void setOrders(Set<Order> orders) {
this.orders = orders;
} /*************** 使用table生成主键的策略 *******************************/
// @TableGenerator(name="ID_GENARATER",
// table="jpa_id_generators",
// pkColumnName="PK_NAME", //指定主键键的列
// pkColumnValue="CUSTOMER_ID", //指定主键的行(列的哪一行)
// valueColumnName="PK_VALUE", //指定主键值的列
// allocationSize=100) //主键增加的大小,默认为50
// @GeneratedValue(strategy=GenerationType.TABLE,generator="ID_GENARATER")
// //generator与@TableGenerator的name对应
/************************************/
@GeneratedValue(strategy = GenerationType.AUTO)
@Id
public int getId() {
return id;
} public void setId(int id) {
this.id = id;
} @Column(name = "last_name")
public String getLastName() {
return lastName;
} public void setLastName(String lastName) {
this.lastName = lastName;
} public String getEmail() {
return email;
} public void setEmail(String email) {
this.email = email;
} public int getAge() {
return age;
} public void setAge(int age) {
this.age = age;
} @Temporal(TemporalType.DATE)
public Date getBirthday() {
return birthday;
} public void setBirthday(Date birthday) {
this.birthday = birthday;
} @Temporal(TemporalType.TIMESTAMP)
public Date getCreatTime() {
return creatTime;
} public void setCreatTime(Date creatTime) {
this.creatTime = creatTime;
} @Override
public String toString() {
return "Customer [id=" + id + ", lastName=" + lastName + ", email=" + email + ", age=" + age + ", birthday="
+ birthday + ", creatTime=" + creatTime + "]";
} }
Order
package entity; import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table; @Table(name="JPA_ORDERS")
@Entity
public class Order { private Integer id;
private String orderName; // private Customer customer; //暂时注掉。测试一对多 @GeneratedValue
@Id
public Integer getId() {
return id;
} public void setId(Integer id) {
this.id = id;
} @Column(name="ORDER_NAME")
public String getOrderName() {
return orderName;
} public void setOrderName(String orderName) {
this.orderName = orderName;
} /**
* @JoinColumn //映射外键
* @ManyToOne //映射一对多的关系
* ***/
// @JoinColumn(name="CUSTOMER_ID")
// @ManyToOne(fetch=FetchType.LAZY)
// public Customer getCustomer() {
// return customer;
// }
//
// public void setCustomer(Customer customer) {
// this.customer = customer;
// } }
manyToOneTest
package test; import java.util.Date; import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence; import org.junit.After;
import org.junit.Before;
import org.junit.Test; import entity.Customer;
import entity.Order; public class japManyToOneTest { private EntityManagerFactory entityManagerFactory;
private EntityManager entityManager;
private EntityTransaction entityTransaction; @Before
public void init() {
entityManagerFactory = Persistence.createEntityManagerFactory("JPA");
entityManager = entityManagerFactory.createEntityManager();
entityTransaction = entityManager.getTransaction();
entityTransaction.begin();
} @After
public void distory() {
entityTransaction.commit();
entityManager.close();
entityManagerFactory.close(); }
/* (多对一测试,由于测试一对一多,把Order中的Customer注释了)
@Test
public void testManyToOneUpdate() {
Order order = entityManager.find(Order.class, 6);
order.getCustomer().setLastName("MM");
} //* 不能删除1的一方,由于有外键关联 @Test
public void testManyToOneDelete() {
Order order = entityManager.find(Order.class, 5);
entityManager.remove(order);
// Customer customer = entityManager.find(Customer.class, 4);
// entityManager.remove(customer); } //* default user left out select we cen user the parameter of fecth="lazy"
// * at @manytoOne(fecth="lazy")
@Test
public void testManyToOneFind() {
Order order = entityManager.find(Order.class, 5);
System.out.println(order); System.out.println(order.getCustomer().getLastName());
} // * 对于多对一,建议先保存1的一端,然后保存多的一端。 (这样就不会多出额外的update语句) 及让多的一方维护关系 @Test
public void ManyToOnePersistence() {
Customer customer = new Customer();
customer.setAge(23);
customer.setEmail("qq@163.com");
customer.setLastName("QQ");
customer.setBirthday(new Date());
customer.setCreatTime(new Date()); Order order1 = new Order();
order1.setOrderName("OO_order_01"); Order order2 = new Order();
order2.setOrderName("OO_order_02"); // 设置关联关系
order1.setCustomer(customer);
order2.setCustomer(customer); // 保存
entityManager.persist(customer);
entityManager.persist(order1);
entityManager.persist(order2); }
*/
}
oneToManyTest
package test; import static org.junit.Assert.*; import java.util.Date;
import java.util.Set; import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence; import org.junit.After;
import org.junit.Before;
import org.junit.Test; import entity.Customer;
import entity.Order; public class japOneToManyTest { private EntityManagerFactory entityManagerFactory;
private EntityManager entityManager;
private EntityTransaction entityTransaction; @Before
public void init() {
entityManagerFactory = Persistence.createEntityManagerFactory("JPA");
entityManager = entityManagerFactory.createEntityManager();
entityTransaction = entityManager.getTransaction();
entityTransaction.begin();
}
@After
public void distory() {
entityTransaction.commit();
entityManager.close();
entityManagerFactory.close(); } @Test
public void testOneToMany(){
Customer customer = entityManager.find(Customer.class, 15) ;
Set<Order> orders = customer.getOrders();
Order order = orders.iterator().next();
order.setOrderName("AAAAAAAAAAAAAAAA");
//System.out.println(order);
}
/**
* 一对多,默认删除一的一方,多的一方外键会置空,一的一方会被删除,多的一方保留,外键置空
* 可以通过级联删除一并删除(在@onetomany(cascade={CascadeType.REMOVE}))
*/
@Test
public void testOneToManyDelete(){
Customer customer = entityManager.find(Customer.class, 12);
entityManager.remove(customer); } /**
* default staregt is lazy 默认关联多的一方使用lazy加载策略
* @throws Exception
*/
@Test
public void testOneToManyFind() throws Exception {
Customer customer = entityManager.find(Customer.class, 2);
System.out.println(customer.getLastName()); //获取一对多的多。 default staregt is lazy
System.out.println(customer.getOrders().size()); } /**
* 对于一对多, 保存时,无论是先保存一的一端,还是多的一端都会执行update语句
* 因为多的一端 ,在保存时不会同时插入外键列
*/
@Test
public void testOneToManyPersistence(){
Customer customer = new Customer();
customer.setAge(23);
customer.setEmail("KKKK@163.com");
customer.setLastName("KKKK");
customer.setBirthday(new Date());
customer.setCreatTime(new Date()); Order order1 = new Order();
order1.setOrderName("DDDD_01");
Order order2 = new Order();
order2.setOrderName("DDDD_02"); //建立关系
customer.getOrders().add(order1);
customer.getOrders().add(order2);
//执行保存
entityManager.persist(customer);
entityManager.persist(order1);
entityManager.persist(order2); } }
jpa 一对多and 多对一的更多相关文章
- JPA一对多和多对一关系
1-m:多的一方为关系维护端,关系维护端负责外键纪录的更新,关系被维护端没有权力更新外键纪录. 维护端注解 @OneToMany(cascade = { CascadeType.PERSIST, Ca ...
- JPA 一对多、多对一注解
1. @OneToMany @OneToMany 是属性或方法级别的注解,用于定义源实体与目标实体是一对多的关系. 参数 类型 描述 targetEntity Class 源实体关联的目标实体类型,默 ...
- JPA中映射关系详细说明(一对多,多对一,一对一、多对多)、@JoinColumn、mappedBy说明
JPA中的映射关系 jpa中维护one to one ,one to many, many to one ,many to many 四种映射关系. 在每个关系中,双方中的一方在其表中拥有连接列.那么 ...
- Spring Boot 入门系列(二十八) JPA 的实体映射关系,一对一,一对多,多对多关系映射!
前面讲了Spring Boot 使用 JPA,实现JPA 的增.删.改.查的功能,同时也介绍了JPA的一些查询,自定义SQL查询等使用.JPA使用非常简单,功能非常强大的ORM框架,无需任何数据访问层 ...
- PringData JPA一对多多对一多对多关联
一.一对多.多对一 1.Country实体类 2.City实体类 3.CountryDao层 4.CityDao层 5.Controller package com.zn.controller; im ...
- SpringData JPA一对多多对一多对多关联
一.一对多.多对一 1.Country实体类 2.City实体类 3.CountryDao层 4.CityDao层 5.Controller package com.zn.controller; im ...
- Hibernate框架--关联映射,一对多,多对多 inverse cascade
回顾Hibernate: 1. hibernate开发环境搭建 ----> 引入jar: hibernate.jar + required + jpa + 驱动包 ---> hiberna ...
- 07-hibernate注解-一对多(多对一)双向外键关联
一对多(多对一)双向外键 多方:多方持有一方的引用. @ManyToOne(cascade={CasCadeType.ALL},fetch=FetchType.EAGER) @JoinColumn(n ...
- JPA中实现双向多对多的关联关系(附代码下载)
场景 JPA入门简介与搭建HelloWorld(附代码下载): https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/103473937 ...
随机推荐
- hdu1097
hdu1097 求a^b的末位数 打表O(1) import java.util.*; public class Main { static int [][]a = new int[15][15]; ...
- js操作链接url
使用js对当前的URL进行操作,可以使用内置对象window.location: window.location有以下属性: window.location.href:取得当前地址栏中的完整URL,可 ...
- 时间操作(JavaScript版)—年月日三级联动(默认显示系统时间)
版权声明:本文为博主原创文章,未经博主同意不得转载. https://blog.csdn.net/wangshuxuncom/article/details/35263317 这个功能 ...
- sqlserver中numeric字段截取
方法一:convert(float,字段名) as 别名 select convert(float,round(10.123232,2)) 结果:10.12 select convert(float, ...
- Linux 性能工具安装部署
docker 一.运行docker Linux内核版本需要在3.8以上,针对centos6.5 内核为2.6的系统需要先升级内核.不然会特别卡 在yum的ELRepo源中,有mainline(4.5) ...
- JUC集合之 CopyOnWriteArrayList
CopyOnWriteArrayList介绍 它相当于线程安全的ArrayList.和ArrayList一样,它是个可变数组:但是和ArrayList不同的时,它具有以下特性: 它最适合于具有以下特征 ...
- markdown 知识点
符号 说明 作用 ___ 三个下划线 一条直线 * 或_ 1个星号 或 1个下划线 文字斜体 ** 或__ 2个星号 或 2个下划线 文字加粗 全角2个空格 缩进2个汉字 竖线之间加3个间隔符放在第二 ...
- winform 子窗体刷新父窗体的数据
建一个接口 比如 iMainForm接口内声明个方法 比如 Refresh()主窗体 实现这个接口 主窗体打开子窗体时这样写 子窗体.Owner = this;子窗体.ShowDialog(); -- ...
- 49个你应该了解的Android Studio技巧、插件与资源 http://www.apkbus.com/blog-822721-72630.html (出处: 安卓巴士 - 安卓开发 - Android开发 - 安卓 - 移动互联网门户)
49个你应该了解的Android Studio技巧.插件与资源http://www.apkbus.com/blog-822721-72630.html(出处: 安卓巴士 - 安卓开发 - Androi ...
- Mybatis连接Oracle实现增删改查实践
1. 首先要在项目中增加Mybatis和Oracle的Jar文件 这里我使用的版本为ojdbc7 Mybatis版本为:3.2.4 2. 在Oracle中创建User表 create table T_ ...