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 ...
随机推荐
- RadioButtonFor绑定值
<div class="form-group"> <label class="control-label col-md-2">是否< ...
- linux crontab定时任务调用CI框架PHP代码
*****监控项目中使用*****: sudo crontab -u wangyan -e i 5,25,45 * * * * wget http://xxx.xxx.com/xxx/xx Esc : ...
- Caffe 源碼閱讀(四) Layer.hpp Layer.cpp
1.Setup() Layer初始化参数 (1.完成层参数的读入.处理 2.设置底层顶层的shape,在前向传播前完成) InitMutex CheckBolbCounts: LayerSetup:d ...
- STM32启动代码分析 IAR 比较好
stm32启动代码分析 (2012-06-12 09:43:31) 转载▼ 最近开始使用ST的stm32w108芯片(也是一款zigbee芯片).开始看他的启动代码看的晕晕呼呼呼的. 还好在c ...
- 关于Autorun.inf文件
配置Autorun.inf文件可以使双击磁盘时,自动运行某一应用程序.但是现在只支持CD或者DVD媒体了(以前硬盘也可以) 关于Autorun.inf的组成部分可以参考https://msdn.mic ...
- GWAS Simulation
comvert hmp to ped1, ped2, map fileSB1.ped, SB2.ped, SB.map 1, choose 20 markers for 30 times(WD: /s ...
- python 3 学习笔记(一)
由于之前学过python2,因此今天就想记录下第一天学习python3过程中的遇到的不同和之前没有太掌握的基础知识. python2和python3的语法区别 print语句 在Python2里,pr ...
- @SuppressWarnings("deprecation")
在Java编译过程中会出现很多警告,有很多是安全的,但是每次编译有很多警告影响我们对error的过滤和修改,我们可以在代码中加上 @SuppressWarnings("XXXX") ...
- pyside窗口关闭触发事件
窗口关闭事件本质上是重写了类内部的closeEvent方法,可以通过重写这个类去实现其他你想要的关闭事件. 下面的例子实现了一个简单的窗口,并为窗口添加了关闭时弹出提示框的功能. import sys ...
- CSS初体验
经过学习,我对css有了初步的认识.css是层叠样式表(Cascading Style Sheets的缩写,它用于HTML元素的显示形式,是W3C推出的格式化的标准技术.CSS现在已经被大多数浏览器所 ...