JPA(Hibernate) @OneToMany 两种例子
环境:Spring Data Jpa,hibernate或者其他jpa实现也是一样的;Spring Boot
场景:User和Role,一个User要对应多个Role。
第一种方式,没有中间关系表,直接在role表中添加一个user_id字段
User:
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.util.HashSet;
import java.util.Set;
/**
* Created by zhangpeng on 16-6-15.
*/
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
// The user email
@NotNull
private String email;
// The user name
@NotNull
private String name;
private String password;
@OneToMany(mappedBy = "user", cascade = {CascadeType.ALL}, fetch = FetchType.EAGER)
private Set<Role> roles = new HashSet<>();
//add getter and setter
}
Role:
import javax.persistence.*;
/**
* Created by zhangpeng on 16-6-17.
*/
@Entity
@Table(name = "roles")
public class Role {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
Long id;
String roleName;
@ManyToOne
@JoinColumn(name = "user_id")
User user;
//add getter and setter
}
需要注意User类中mappedBy = "user",这个user就是Role中所持有的User对象的名字。Role中@JoinColumn(name = "user_id") 是指定role表中user标识符的字段名。cascade = {CascadeType.ALL}是用来设定级联操作的,这里开启了所有的级联操作。fetch = FetchType.EAGER是用来设置加载类型的。默认是懒加载,如果是懒加载,那就意味着User里的roles在你查询出来这个user时不同时查询出来,而是等访问user里的roles对象时才进行加载。我这里设置的是查询user时就把roles加载过来。
第二种,个人感觉更好一点的,user和role都不持有对方的引用,而是生成中间表:
User:
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.util.HashSet;
import java.util.Set;
/**
* Created by zhangpeng on 16-6-15.
*/
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
// The user email
@NotNull
private String email;
// The user name
@NotNull
private String name;
private String password;
// private String role;
@OneToMany( cascade = {CascadeType.ALL}, fetch = FetchType.EAGER)
private Set<Role> roles = new HashSet<>();
//add getter and setter
}
Role:
import javax.persistence.*;
/**
* Created by zhangpeng on 16-6-17.
*/
@Entity
@Table(name = "roles")
public class Role {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
Long id;
String roleName;
// @ManyToOne
// @JoinColumn(name = "user_id")
// User user;
// public User getUser() {
// return user;
// }
//
// public void setUser(User user) {
// this.user = user;
// }
//add getter and setter
}
这样就可以了。
测试:
import com.guduo.fenghui.dao.RoleDao;
import com.guduo.fenghui.dao.UserDao;
import com.guduo.fenghui.entity.Role;
import com.guduo.fenghui.entity.User;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
@WebAppConfiguration
public class Test {
@Autowired
UserDao userDao;
@Autowired
RoleDao roleDao;
@Test
public void test() {
User user = new User();
user.setEmail("csonezp@gmail.com");
user.setName("zhangpeng");
user.setPassword("123456");
for (int i = 0; i <= 2; i++) {
Role role = new Role();
role.setRoleName(i + "j");
//如果选择的是第一种方式,那要加上这一句。因为第一种方式配置的有mappedby,控制权是在role这边
// role.setUser(user);
user.getRoles().add(role);
}
userDao.save(user);
user = userDao.findByName("zhangpeng");
Assert.assertEquals(user.getRoles().size(), 3);
user.getRoles().get(0).setRoleName("asdasd");
userDao.save(user);
user = userDao.findByName("zhangpeng");
Assert.assertEquals("asdasd", user.getRoles().get(0).getRoleName());
userDao.delete(user.getId());
}
}
这一段测试代码中,体现了级联插入,级联查询,级联更新,级联删除。
JPA(Hibernate) @OneToMany 两种例子的更多相关文章
- Hibernate中两种获取Session的方式
转自:https://www.jb51.net/article/130309.htm Session:是应用程序与数据库之间的一个会话,是hibernate运作的中心,持久层操作的基础.对象的生命周期 ...
- Spring整合Hibernate的两种方式
在使用spring注解整合hibernate时出现"org.hibernate.MappingException: Unknown entity: com.ssh.entry.Product ...
- Hibernate 的两种配置
前言:不管是注解配置还是xml,都是告诉hibernate你想创建什么样的数据表,几张数据表中的关系是什么,仅此而已,剩下的不过就是hibernate的优化了. 所以从创建数据表的ddl语句和数据表的 ...
- Spring Data Jpa(Hibernate) OneToMany
这个其实非常简单.假设有topic 和 subscriber两个实体类,不考虑关联关系,则连个类的代码如下: /** * Created by csonezp on 2017/8/31. */ @En ...
- jpa/hibernate @onetomany 使用left join 添加多条件,可以使用过滤器filters (with-clause not allowed on fetched associations; use filters异常信息)
package com.ipinyou.mip.dataAsset.campaignManagement.entity; import com.ipinyou.mip.utils.NumberUtil ...
- Hibernate中两种删除用户的方式
第一种,是比较传统的,先根据主键列进行查询到用户,在进行删除用户 //删除数据 public void deleteStudent(String sno) { init() ; Student qu ...
- hibernate级联查询映射的两种方式
Hibernate主要支持两种查询方式:HQL查询和Criteria查询.前者应用较为广发,后者也只是调用封装好的接口. 现在有一个问题,就是实现多表连接查询,且查询结果集不与任何一个实体类对应,怎么 ...
- Hibernate(八)--session的两种获取方式
openSession getCurrentSession Hibernate有两种方式获得session,分别是: openSession和getCurrentSession他们的区别在于1. 获取 ...
- 【JPA】两种不同的实现jpa的配置方法
两种不同的实现jpa的配置方法 第一种: com.mchange.v2.c3p0.ComboPooledDataSource datasource.connection.driver_class=co ...
随机推荐
- (zhuan)Python 虚拟环境:Virtualenv
Python 虚拟环境:Virtualenv zhuanzi: http://liuzhijun.iteye.com/blog/1872241 virtualenv virtualenv用于创建独立的 ...
- win7 64位安装pygame
需要的工具包 Python安装包 Pip安装包(版本无要求) Pygame安装包(版本需要与python匹配) http://jingyan.baidu.com/article/425e69e6ed3 ...
- Loadrunner 脚本错误问题汇总(非原创,部分转自互联网)
在运行脚本回放过程中,有时会出现错误,这在实际测试中是不可避免的,毕竟自动录制生成的脚本难免会有问题,需要运行脚本进行验证,把问题都解决后才加入到场景中进行负载测试.下面结合常用的协议(如Web.We ...
- 快速上手RaphaelJS--Instant RaphaelJS Starter翻译(三)
(目前发现一些文章被盗用的情况,我们将在每篇文章前面添加原文地址,本文源地址:http://www.cnblogs.com/idealer3d/p/Instant_RaphaelJS_Starter3 ...
- Unity3D-坐标转换笔记
Transform.TransformPoint 作用 : 将一个点从以自身为坐标系的本地坐标转换成世界坐标 Transform.InverseTransformPoint 作用 : 将一个点从世界坐 ...
- Largest Rectangle in Histogram
Given n non-negative integers representing the histogram's bar height where the width of each bar is ...
- OpenMP共享内存并行编程详解
实验平台:win7, VS2010 1. 介绍 平行计算机可以简单分为共享内存和分布式内存,共享内存就是多个核心共享一个内存,目前的PC就是这类(不管是只有一个多核CPU还是可以插多个CPU,它们都有 ...
- android 保存文件的各种目录列表
一般的,我们可以通过context和Environment来获取要保存文件的目录 ($rootDir) +- /data -> Environment.getDataDirectory() | ...
- Python 中的虚拟环境
检查系统是否安装了virtualenv: $ virtualenv --version 创建虚拟环境venv(名字可以随便取,一般为venv): $ virtualenv venv 使用虚拟环境ven ...
- Java JDBC链接数据库
1.注册驱动Class.forname("com.mysql.jdbc.Driver");//这是连接mysql数据库的驱动2.获取数据库连接java.sql.Connectio ...