使用注解的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文件 ♣ ...
随机推荐
- something good
CF292A CF304B CF383A CF409D CF409F CF632A CF652B CF656A CF656B CF656D CF659A CF678A CF697A CF735D CF ...
- [opengl] 画一个可移动的自行车 二维几何变换(平移、旋转、缩放)
#include <cmath> #include "glut.h" #include "iostream" using namespace std ...
- Android系列教程之前言
内容转载自我自己的博客 目前安卓的主流开发语言是Java,在正式开始Android系列的教程之前,需要知道一些基本内容 Android介绍 Android['ændrɔid] 是一个基于Linux 内 ...
- spring applicationContext.xml文件移到resources目录下
SpringMVC的框架默认目录结构 修改后的目录结构及web.xml 同时在pom里的配置:将resources目录打包到web-inf/classes目录下<resources> ...
- sql server还原数据库(请选择用于还原的备份集)
还原数据库的时候明明选择了备份集,还是提示未选择还原的备份集 后来查了下,是因为我本地有两个数据库(2008R2和2014),对应的两个数据库实例.而还原bak是sqlserver2014的备份,我默 ...
- AIX7.1安装zabbix_agent3.4
1.在zabbix官网https://www.zabbix.com/download下载Zabbix pre-compiled agents 2.Zabbix pre-compiled agents安 ...
- Python识别璇玑图中诗的数量
一.璇玑图简介 璇玑图的读法有很多,这里我使用七七棋盘格的读法,在璇玑图中分离出一个七七棋盘格,如下表 吏 官 同 流 污 合 玩 痞 悍 蒙 骗 造 假 蛋 鸡 宴 请 客 友 朋 远 戚 偏 正 ...
- HttpsUtils
package io.renren.modules.jqr.util; import java.io.BufferedReader; import java.io.InputStream; impor ...
- .net core 实现基于 cron 表达式的任务调度
.net core 实现基于 cron 表达式的任务调度 Intro 上次我们实现了一个简单的基于 Timer 的定时任务,详细信息可以看这篇文章. 但是使用过程中慢慢发现这种方式可能并不太合适,有些 ...
- .net core 基于 IHostedService 实现定时任务
.net core 基于 IHostedService 实现定时任务 Intro 从 .net core 2.0 开始,开始引入 IHostedService,可以通过 IHostedService ...