使用注解的Hibernate one-to-many映射
One to many映射关系指的是两个实体间一个实体可以和多个实体有关联关系,但是多的这一端只能和一的这一端的一个实例有关系。它是一个1 到 n的关系。例如在任何的公司员工可以注册多个银行账户,一个银行账户只能和一个员工相关联,在这篇文章中我们将会学习怎么在Hibernate3中建立这种映射关系。
问题陈述
设计解决方案
使用外键连接
- package hibernate.test.oneToMany.foreignKeyAsso;
- import java.io.Serializable;
- import java.util.Set;
- import javax.persistence.CascadeType;
- import javax.persistence.Column;
- import javax.persistence.Entity;
- 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.UniqueConstraint;
- @Entity(name = "ForeignKeyAssoEntity")
- @Table(name = "Employee", uniqueConstraints = {
- @UniqueConstraint(columnNames = "ID"),
- @UniqueConstraint(columnNames = "EMAIL") })
- public class EmployeeEntity implements Serializable {
- private static final long serialVersionUID = -1798070786993154676L;
- @Id
- @GeneratedValue(strategy = GenerationType.IDENTITY)
- @Column(name = "ID", unique = true, nullable = false)
- private Integer employeeId;
- @Column(name = "EMAIL", unique = true, nullable = false, length = 100)
- private String email;
- @Column(name = "FIRST_NAME", unique = false, nullable = false, length = 100)
- private String firstName;
- @Column(name = "LAST_NAME", unique = false, nullable = false, length = 100)
- private String lastName;
- @OneToMany(cascade=CascadeType.ALL)
- @JoinColumn(name="EMPLOYEE_ID")
- private Set<AccountEntity> accounts;
- public Integer getEmployeeId() {
- return employeeId;
- }
- public void setEmployeeId(Integer employeeId) {
- this.employeeId = employeeId;
- }
- public String getEmail() {
- return email;
- }
- public void setEmail(String email) {
- this.email = email;
- }
- public String getFirstName() {
- return firstName;
- }
- public void setFirstName(String firstName) {
- this.firstName = firstName;
- }
- public String getLastName() {
- return lastName;
- }
- public void setLastName(String lastName) {
- this.lastName = lastName;
- }
- public Set<AccountEntity> getAccounts() {
- return accounts;
- }
- public void setAccounts(Set<AccountEntity> accounts) {
- this.accounts = accounts;
- }
- }
Account实体
- package hibernate.test.oneToMany.foreignKeyAsso;
- import java.io.Serializable;
- import javax.persistence.Column;
- import javax.persistence.Entity;
- import javax.persistence.GeneratedValue;
- import javax.persistence.GenerationType;
- import javax.persistence.Id;
- import javax.persistence.ManyToOne;
- import javax.persistence.Table;
- import javax.persistence.UniqueConstraint;
- @Entity(name = "ForeignKeyAssoAccountEntity")
- @Table(name = "ACCOUNT", uniqueConstraints = {
- @UniqueConstraint(columnNames = "ID")})
- public class AccountEntity implements Serializable
- {
- private static final long serialVersionUID = -6790693372846798580L;
- @Id
- @GeneratedValue(strategy = GenerationType.IDENTITY)
- @Column(name = "ID", unique = true, nullable = false)
- private Integer accountId;
- @Column(name = "ACC_NUMBER", unique = true, nullable = false, length = 100)
- private String accountNumber;
- @ManyToOne
- private EmployeeEntity employee;
- public Integer getAccountId() {
- return accountId;
- }
- public void setAccountId(Integer accountId) {
- this.accountId = accountId;
- }
- public String getAccountNumber() {
- return accountNumber;
- }
- public void setAccountNumber(String accountNumber) {
- this.accountNumber = accountNumber;
- }
- public EmployeeEntity getEmployee() {
- return employee;
- }
- public void setEmployee(EmployeeEntity employee) {
- this.employee = employee;
- }
- }
测试代码
- package hibernate.test.oneToMany;
- import hibernate.test.HibernateUtil;
- import hibernate.test.oneToMany.foreignKeyAsso.AccountEntity;
- import hibernate.test.oneToMany.foreignKeyAsso.EmployeeEntity;
- import java.util.HashSet;
- import java.util.Set;
- import org.hibernate.Session;
- public class TestForeignKeyAssociation
- {
- public static void main(String[] args)
- {
- Session session = HibernateUtil.getSessionFactory().openSession();
- session.beginTransaction();
- AccountEntity account1 = new AccountEntity();
- account1.setAccountNumber("Account detail 1");
- AccountEntity account2 = new AccountEntity();
- account2.setAccountNumber("Account detail 2");
- AccountEntity account3 = new AccountEntity();
- account3.setAccountNumber("Account detail 3");
- //Add new Employee object
- EmployeeEntity firstEmployee = new EmployeeEntity();
- firstEmployee.setEmail("demo-user-first@mail.com");
- firstEmployee.setFirstName("demo-one");
- firstEmployee.setLastName("user-one");
- EmployeeEntity secondEmployee = new EmployeeEntity();
- secondEmployee.setEmail("demo-user-second@mail.com");
- secondEmployee.setFirstName("demo-two");
- secondEmployee.setLastName("user-two");
- Set<AccountEntity> accountsOfFirstEmployee = new HashSet<AccountEntity>();
- accountsOfFirstEmployee.add(account1);
- accountsOfFirstEmployee.add(account2);
- Set<AccountEntity> accountsOfSecondEmployee = new HashSet<AccountEntity>();
- accountsOfSecondEmployee.add(account3);
- firstEmployee.setAccounts(accountsOfFirstEmployee);
- secondEmployee.setAccounts(accountsOfSecondEmployee);
- //Save Employee
- session.save(firstEmployee);
- session.save(secondEmployee);
- session.getTransaction().commit();
- HibernateUtil.shutdown();
- }
- }
- Output:
- Hibernate: insert into Employee (EMAIL, FIRST_NAME, LAST_NAME) values (?, ?, ?)
- Hibernate: insert into ACCOUNT (ACC_NUMBER, employee_ID) values (?, ?)
- Hibernate: insert into ACCOUNT (ACC_NUMBER, employee_ID) values (?, ?)
- Hibernate: insert into Employee (EMAIL, FIRST_NAME, LAST_NAME) values (?, ?, ?)
- Hibernate: insert into ACCOUNT (ACC_NUMBER, employee_ID) values (?, ?)
- Hibernate: update ACCOUNT set EMPLOYEE_ID=? where ID=?
- Hibernate: update ACCOUNT set EMPLOYEE_ID=? where ID=?
- Hibernate: update ACCOUNT set EMPLOYEE_ID=? where ID=?
使用关联表
- package hibernate.test.oneToMany.joinTable;
- import java.io.Serializable;
- import java.util.Set;
- import javax.persistence.CascadeType;
- import javax.persistence.Column;
- import javax.persistence.Entity;
- import javax.persistence.GeneratedValue;
- import javax.persistence.GenerationType;
- import javax.persistence.Id;
- import javax.persistence.JoinColumn;
- import javax.persistence.JoinTable;
- import javax.persistence.OneToMany;
- import javax.persistence.Table;
- import javax.persistence.UniqueConstraint;
- @Entity(name = "JoinTableEmployeeEntity")
- @Table(name = "Employee", uniqueConstraints = {
- @UniqueConstraint(columnNames = "ID"),
- @UniqueConstraint(columnNames = "EMAIL") })
- public class EmployeeEntity implements Serializable
- {
- private static final long serialVersionUID = -1798070786993154676L;
- @Id
- @GeneratedValue(strategy = GenerationType.IDENTITY)
- @Column(name = "ID", unique = true, nullable = false)
- private Integer employeeId;
- @Column(name = "EMAIL", unique = true, nullable = false, length = 100)
- private String email;
- @Column(name = "FIRST_NAME", unique = false, nullable = false, length = 100)
- private String firstName;
- @Column(name = "LAST_NAME", unique = false, nullable = false, length = 100)
- private String lastName;
- @OneToMany(cascade=CascadeType.ALL)
- @JoinTable(name="EMPLOYEE_ACCOUNT", joinColumns={@JoinColumn(name="EMPLOYEE_ID", referencedColumnName="ID")}
- , inverseJoinColumns={@JoinColumn(name="ACCOUNT_ID", referencedColumnName="ID")})
- private Set<AccountEntity> accounts;
- public Integer getEmployeeId() {
- return employeeId;
- }
- public void setEmployeeId(Integer employeeId) {
- this.employeeId = employeeId;
- }
- public String getEmail() {
- return email;
- }
- public void setEmail(String email) {
- this.email = email;
- }
- public String getFirstName() {
- return firstName;
- }
- public void setFirstName(String firstName) {
- this.firstName = firstName;
- }
- public String getLastName() {
- return lastName;
- }
- public void setLastName(String lastName) {
- this.lastName = lastName;
- }
- public Set<AccountEntity> getAccounts() {
- return accounts;
- }
- public void setAccounts(Set<AccountEntity> accounts) {
- this.accounts = accounts;
- }
- }
Account实体
- package hibernate.test.oneToMany.joinTable;
- import java.io.Serializable;
- import javax.persistence.Column;
- import javax.persistence.Entity;
- import javax.persistence.GeneratedValue;
- import javax.persistence.GenerationType;
- import javax.persistence.Id;
- import javax.persistence.Table;
- import javax.persistence.UniqueConstraint;
- @Entity(name = "JoinTableAccountEntity")
- @Table(name = "ACCOUNT", uniqueConstraints = {
- @UniqueConstraint(columnNames = "ID")})
- public class AccountEntity implements Serializable
- {
- private static final long serialVersionUID = -6790693372846798580L;
- @Id
- @GeneratedValue(strategy = GenerationType.IDENTITY)
- @Column(name = "ID", unique = true, nullable = false)
- private Integer accountId;
- @Column(name = "ACC_NUMBER", unique = true, nullable = false, length = 100)
- private String accountNumber;
- public Integer getAccountId() {
- return accountId;
- }
- public void setAccountId(Integer accountId) {
- this.accountId = accountId;
- }
- public String getAccountNumber() {
- return accountNumber;
- }
- public void setAccountNumber(String accountNumber) {
- this.accountNumber = accountNumber;
- }
- }
在配置文件中配置实体,我们已经有了两个在运行时的实体,我们必须在配置文件中增加他们。请注意只有一个集合实体可以在配置文件中配置,否则会有意外的情况发生
- < ?xml version="1.0" encoding="utf-8"?>
- < !DOCTYPE hibernate-configuration PUBLIC
- "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
- "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
- <hibernate-configuration>
- <session-factory>
- <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
- <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernatetest</property>
- <property name="hibernate.connection.password">XXXXXX</property>
- <property name="hibernate.connection.username">root</property>
- <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
- <property name="show_sql">true</property>
- <property name="hbm2ddl.auto">create</property>
- <mapping clas="hibernate.test.oneToMany.foreignKeyAsso.AccountEntity"></mapping>
- <mapping clas="hibernate.test.oneToMany.foreignKeyAsso.EmployeeEntity"></mapping>
- </session-factory>
- </hibernate-configuration>
测试代码:
- package hibernate.test.oneToMany;
- import hibernate.test.HibernateUtil;
- import hibernate.test.oneToMany.joinTable.AccountEntity;
- import hibernate.test.oneToMany.joinTable.EmployeeEntity;
- import java.util.HashSet;
- import java.util.Set;
- import org.hibernate.Session;
- public class TestJoinTable
- {
- public static void main(String[] args)
- {
- Session session = HibernateUtil.getSessionFactory().openSession();
- session.beginTransaction();
- AccountEntity account1 = new AccountEntity();
- account1.setAccountNumber("123-345-65454");
- AccountEntity account2 = new AccountEntity();
- account2.setAccountNumber("123-345-6542222");
- //Add new Employee object
- EmployeeEntity emp = new EmployeeEntity();
- emp.setEmail("demo-user@mail.com");
- emp.setFirstName("demo");
- emp.setLastName("user");
- Set<AccountEntity> accounts = new HashSet<AccountEntity>();
- accounts.add(account1);
- accounts.add(account2);
- emp.setAccounts(accounts);
- //Save Employee
- session.save(emp);
- session.getTransaction().commit();
- HibernateUtil.shutdown();
- }
- }
- Output:
- Hibernate: insert into Employee (EMAIL, FIRST_NAME, LAST_NAME) values (?, ?, ?)
- Hibernate: insert into ACCOUNT (ACC_NUMBER) values (?)
- Hibernate: insert into ACCOUNT (ACC_NUMBER) values (?)
- Hibernate: insert into EMPLOYEE_ACCOUNT (EMPLOYEE_ID, ACCOUNT_ID) values (?, ?)
- Hibernate: insert into EMPLOYEE_ACCOUNT (EMPLOYEE_ID, ACCOUNT_ID) values (?, ?)
使用注解的Hibernate one-to-many映射的更多相关文章
- hibernate的对象/关系映射结果为空,exists查不到值的问题-20190823
1: hibernate的对象/关系映射 情景:在使用@onetotone/@manytonone时关联结果为空 原因:在使用这个注解的时候,默认的时crossjoin(交叉连接),在进行查询时以及排 ...
- Hibernate多对多关系映射(建表)
下边讲述Hibernate多对多关系映射. 多对多关系的表的结构为: 两个实体表,还包含一个关系表,关系表为复合主键,如果要使用Hibernate多对多关系映射,则关系表必须只包含两个字段,如果生成了 ...
- Hibernate入门3.配置映射文件深入
Hibernate入门3.配置映射文件深入 2013.11.27 前言: 之前的两节是在Java项目中如何使用hibernate,并且通过一个简单地项目实践,期间有很多的错误,一般都是因为配置包的问题 ...
- 菜鸟学习Hibernate——多对多关系映射
Hibernate中的关系映射,最常见的关系映射之一就是多对多关系映射例如用户与角色的关系,一个用户对应多个角色,一个角色对应多个用户.如图: Hibernate中如何来映射这两个的关系呢? 下面就为 ...
- 菜鸟学习Hibernate——一对多关系映射
Hibernate中的关系映射,最常见的关系映射之一就是一对多关系映射例如学生与班级的关系,一个班级对应多个学生.如图: Hibernate中如何来映射这两个的关系呢? 下面就为大家讲解一下: 1.创 ...
- Hibernate一对一双向关联映射
关键原因在于对象模型具有方向性: 单向:一端只能加载另一端,不能反过来. 双向:两端都可以加载另一端. 问题来了:如何我们想从身份证端(IdCard)加载人(Person),怎么办呢? 下面我们开始介 ...
- Hibernate之1-N关联映射
一.Hibernate之1-N关联映射 1. 哪边是 1 , 哪边是多 ? 须要从业务的角度来说明.比如,Employee 和 Department 之间就是 n-1 的关联关系,Order ...
- Hibernate一对一主键映射
Hibernate一对一主键映射 ------------------------------ -- ...
- Hibernate一对一外键映射
Hibernate 一对一外键映射 ------------------------------ ----- ...
- Eclipse从数据库逆向生成Hibernate实体类和映射文件(Eclipse插件系列之HibernateTools)
♣下载安装Eclipse插件(HibernateTools) ♣Eclipse连接数据库(Mysql5.7) ♣新建hibernate.properties和hibernate.cfg.xml文件 ♣ ...
随机推荐
- 【投票】你心目中的Excel催化剂价值有多大(附主流国内外收费插件供参考)?
Excel催化剂开发过程中,在前期功能中,也会参考着其他的插件的功能,也略略收集了一些其他插件的功能及价格信息,在当今免费等于鸡肋的时代,为了让大家不受这个免费的错觉影响,不妨以另一种角度去假设一翻, ...
- git,github,gitlab,码云的区别
git 是版本控制工具. github https://github.com/和gitlab https://about.gitlab.com/都是基于git仓库的web开发流程代码托管平台.两者的区 ...
- 如何处理MySQL经常出现CPU占用率达到99%
如何处理MySQL经常出现CPU占用率达到99% 情况说明: 最近在自己购买的linux服务器上捣鼓了一个小项目,按理说不存在CPU占用率会达到100%的情况,但事实就是经常出现. 然后,我第一反应是 ...
- jquery实现最简单的下拉菜单
<!doctype html> <html> <head> <meta charset="utf-8"> <title> ...
- iis8 php-cgi.exe - FastCGI 进程意外退出 500错误解决办法
今天iis服务环境下的网站突然显示200错误php-cgi.exe - FastCGI 进程意外退出,昨天还好好的网站正常,这个问题一直偶尔出现几次,不是很频繁,但是偶尔会出现: 这是由于某些加载库加 ...
- [机器学习] kears入门:用单层网络实现玩具回归
learn from: 莫烦教keras的视频: https://morvanzhou.github.io/tutorials/machine-learning/keras/2-1-regressor ...
- Nginx配置安装(Mac)
我用到的安装工具是:homebrew 真的很方便! 步骤1: 打开终端,输入 brew info nginx结果:我们可以看到,nginx在本地还未安装(Not installed),nginx的来源 ...
- Zabbix利用Windows性能监视器监控各项资源指标
zabbix自带的windows监控模板并没有监控windows cpu使用率的监控 在cmd命令输入perfmon 打开后默认就一项CPU占用的监控,下面以添加硬盘空闲时间做示例 1:监控图形上面右 ...
- 证明线程池ThreadPoolExecutor的核心线程数,最大线程数,队列长度的关系
关于线程池的几个参数,很多人不是很清楚如何配置,他们之间是什么关系,我用代码来证明一下. package www.itbac.com; import java.util.concurrent.*; p ...
- Centos安装git并配置ssh
1.下载git安装包 git-2.9.4.tar.gz 2.解压 tar -xzvf git-2.9.4.tar.gz 3.修改解压后的文件名 mv git-2.9.4 git 4.安装git依赖的库 ...