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 ...
随机推荐
- HTML标签 select 里 动态添加option
HTML标签 select 里 动态添加option: ☆ var today = new Date(); var yearNow = today.getFullYear(); var optiong ...
- SharePoint2010 安装时报“未能启动数据库服务 MSSQL$Sharepoint"解决办法
对于已经安装sql server 的情况 今天装SharePointFoundation遇到“未能启动数据库服务 MSSQL$Sharepoint”搜了下有如下解决办法 “HKLM_Local_Mac ...
- 五、概念数据模型(CDM生成LDM,PDM和OOM)
概念数据模型 概念数据模型(Conceptual Data Model,CDM):表达的是数据整体逻辑结构,该结构独立于任何软件和数据存储结构,即它只是系统分析人员,应用程序设计人员,维护人员和用 ...
- VS2017增加数据库连接串
新装VS2017后,按照三石提供的MVC入门教程,创建MVC应用后,能生成数据库文件(在APP_DATA目录),但无法创建连接,服务器路径一直不正确. 解决方法: 1.重新打开VS2017安装界面,选 ...
- 大快hadoop安装包下载与平台监控参数说明
前阶段用了差不多两周的时间把DKhadoop的运行环境搭建以及安装的各个操作都介绍了一遍.关于DKhadoop安装包下载也只是顺带说了一下,但好像大快搜索的服务器在更新,新的下载页面还不好用!有好些朋 ...
- RK3399 Android 7.1 删除repo后编译报错
CPU:RK3399 系统:Android 7.1 瑞芯微使用的是 repo 来进行代码管理,但我们需要用 git 来管理,所以就删除了 repo,但是编译就报错,如下:Server is alrea ...
- java编码-多重(乱码)
一.1,UTF编码 - 2,ISO解码 - 3,UTF编码 - 4,ISO解码 String ISO = "ISO-8859-1"; String UTF = "UTF- ...
- java jni 调用c++ opencv代码成功范例
java上建立接口定义 package com.dtk; public class Rec { public native String RecImage(String src); public st ...
- ASP 三十二条精华代码 (1)
ASP 三十二条精华代码 (1) 2009-08-10 09:53:03 www.hackbase.com 来源:互联网 1. oncontextmenu="window.event.r ...
- 工欲善其事必先利其器系列之:更换Visual Studio代码风格.
前言:如果你厌倦了默认的VS的背景颜色,可以在studiostyl下载.vssettinggs文件,将其导入VS中,黑色的风格还是蛮不错的,如果用的12的话就没这个必要了我觉得. 从网站下载后会得到扩 ...