JPA 系列教程5-双向一对多
双向一对多的ddl语句
同单向多对一,单向一对多表的ddl语句一致
Product
package com.jege.jpa.one2many;
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.one2many;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
/**
* @author JE哥
* @email 1272434821@qq.com
* @description:双向:一个商品类型下面有n个商品
*/
@Entity
@Table(name = "t_product_type")
public class ProductType {
@Id
@GeneratedValue
private Long id;
private String name;
// 一对多:集合Set
@OneToMany(mappedBy = "type", orphanRemoval = true)
private Set<Product> products = new HashSet<Product>();
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 Set<Product> getProducts() {
return products;
}
public void setProducts(Set<Product> products) {
this.products = products;
}
@Override
public String toString() {
return "ProductType [id=" + id + ", name=" + name + "]";
}
}
One2ManyTest
package com.jege.jpa.one2many;
import java.util.Set;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
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 One2ManyTest {
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");
Product product1 = new Product("商品1", type);
Product product2 = new Product("商品2", type);
entityManager.persist(type);// 持久化状态 商品类型1
entityManager.persist(product1);// 持久化状态
entityManager.persist(product2);// 持久化状态
entityManager.getTransaction().commit();
System.out.println("++++++++++++++++++++");
}
// 级联保存
// 需要先修改ProductType.java类
// @OneToMany(mappedBy = "type",cascade=CascadeType.PERSIST)
@Test
public void persist2() throws Exception {
entityManager = entityManagerFactory.createEntityManager();
entityManager.getTransaction().begin();
ProductType type = new ProductType();
type.setName("商品类型1");
// 建立多方到一方的关系
Product product1 = new Product("商品1", type);
Product product2 = new Product("商品2", type);
// 从一方建立到多方的关系
type.getProducts().add(product1);
type.getProducts().add(product2);// 临时状态
entityManager.persist(type);// 持久化状态
entityManager.getTransaction().commit();
}
// 级联删除
// 需要先修改ProductType.java类
// @OneToMany(mappedBy = "type",cascade=CascadeType.REMOVE)
@Test
public void remove() throws Exception {
entityManager = entityManagerFactory.createEntityManager();
entityManager.getTransaction().begin();
ProductType type = entityManager.find(ProductType.class, 1L);
entityManager.remove(type);
entityManager.getTransaction().commit();
}
// 只删除一方,不能删除一方里面的多方
// 需要先修改ProductType.java类
// @OneToMany(mappedBy = "type")
@Test
public void remove2() throws Exception {
entityManager = entityManagerFactory.createEntityManager();
entityManager.getTransaction().begin();
ProductType type = entityManager.find(ProductType.class, 1L);
String jpql = "update Product set type=null where type=?";
Query query = entityManager.createQuery(jpql);
query.setParameter(1, type);
int update = query.executeUpdate();
System.out.println("修改成功多少条:"+update);
jpql = "delete from ProductType where id=?";
query = entityManager.createQuery(jpql);
query.setParameter(1, type.getId());
update = query.executeUpdate();
System.out.println("删除成功多少条:"+update);
entityManager.getTransaction().commit();
}
// 获取多方,然后删除一条多方
@Test
public void remove3() throws Exception {
entityManager = entityManagerFactory.createEntityManager();
entityManager.getTransaction().begin();
Product product = entityManager.find(Product.class, 1L);
entityManager.remove(product);
entityManager.getTransaction().commit();
}
// 获取一方,通过一方来删除一条多方
//需要先修改ProductType.java类
// @OneToMany(mappedBy = "type", orphanRemoval = true)
@Test
public void remove4() throws Exception {
entityManager = entityManagerFactory.createEntityManager();
entityManager.getTransaction().begin();
Product product = entityManager.find(Product.class, 1L);
ProductType type = entityManager.find(ProductType.class, 1L);
type.getProducts().remove(product);
entityManager.getTransaction().commit();
}
@Test
public void find() throws Exception {
// 不能通过一方获取多方集合是否为null,来判断是否一方是否有多方的数据,只能通过一方获取多方集合.size()来判断
ProductType type = entityManager.find(ProductType.class, 1L);
System.out.println(type);
Set<Product> products = type.getProducts();
if (products.size() > 0) {
System.out.println("当前商品类型下面有商品的");
} else {
System.out.println("当前商品类型下面没有商品的");
}
}
@After
public void tearDown() throws Exception {
if (entityManager != null && entityManager.isOpen())
entityManager.close();
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
if (entityManagerFactory != null && entityManagerFactory.isOpen())
entityManagerFactory.close();
}
}
其他关联项目
- * JPA 系列教程4-单向一对多*
http://blog.csdn.net/je_ge/article/details/53494059 - JPA 系列教程3-单向一对多
http://blog.csdn.net/je_ge/article/details/53493897
源码地址
如果觉得我的文章对您有帮助,请打赏支持。您的支持将鼓励我继续创作!谢谢!
JPA 系列教程5-双向一对多的更多相关文章
- JPA 系列教程4-单向一对多
JPA中的@OneToMany @Target({METHOD, FIELD}) @Retention(RUNTIME) public @interface OneToMany { Class tar ...
- JPA 系列教程21-JPA2.0-@MapKeyColumn
@MapKeyColumn 用@JoinColumn注解和@MapKeyColumn处理一对多关系 ddl语句 CREATE TABLE `t_employee` ( `id` bigint(20) ...
- JPA 系列教程10-双向一对一关联表
双向一对一关联表的ddl语句 CREATE TABLE `t_person` ( `id` bigint(20) NOT NULL AUTO_INCREMENT, `name` varchar(255 ...
- JPA 系列教程9-双向一对一唯一外键
双向一对一唯一外键的ddl语句 CREATE TABLE `t_person` ( `id` bigint(20) NOT NULL AUTO_INCREMENT, `name` varchar(25 ...
- JPA 系列教程7-双向多对多
双向多对多的ddl语句 同单向多对多表的ddl语句一致 Student package com.jege.jpa.many2many; import java.util.HashSet; import ...
- 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 ...
随机推荐
- POJ 1862 Stripies#贪心(水)
(- ̄▽ ̄)-* #include<iostream> #include<cstdio> #include<cmath> #include<algorithm ...
- NSDictionary 的内部实现
NSDictionary是IOS中使用的一种key-value容器,参考cocotron的源代码,NSDictionary使用NSMapTable实现. NSMapTable同样是一个key-valu ...
- DX shader根据顶点设置颜色
matrix ViewProjMatrix; vector Blue = {0.0f, 0.0f, 1.0f, 0.0f}; struct VS_INPUT { vector position : P ...
- EnumPrinters用法
看API描述,不怎么理解,还是在网上找到用法,记载一下: 1: DWORD dwNeeded = 0, dwNum = 0; 2: EnumPrinters(PRINTER_ENUM_LOCAL, N ...
- ejabberd聊天室离线消息
首先,xmpp服务器是基于ejabberd.离线消息模块是mod_interact,原地址地址:https://github.com /adamvduke/mod_interact: 修改后实现群聊离 ...
- js中的随机数
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> ...
- [转载]The Island Castaway mac版解锁
http://blog.sina.com.cn/s/blog_506b3ac90101ke0e.html 1.首先,去安装一个The Island - Castaway™ mac free版,然后打开 ...
- 配置php开发环境
安装apache 1 loadModule 加载php的模块2 addType 告诉apache凡是php结尾的文件都交给php模块执行3 PHPIniDir 告诉apache php.ini的文件在 ...
- python实现邮件发送
实例补充: #**************************利用STMP自动发送邮件******************************import smtplibsmtp = smtp ...
- MFC下DLL编程(图解)
MFC下DLL编程(图解) DLL(Dynamic Link Library,动态链接库)是微软公司为Windows和OS/2操作系统设计一种供应用程序在运行时调用的共享函数库.DLL是应用程序的一种 ...