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 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 getAccounts() {
return accounts;
}
public void setAccounts(Set accounts) {
this.accounts = accounts;
}
}
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("[email protected]");
firstEmployee.setFirstName("demo-one");
firstEmployee.setLastName("user-one");
EmployeeEntity secondEmployee = new EmployeeEntity();
secondEmployee.setEmail("[email protected]");
secondEmployee.setFirstName("demo-two");
secondEmployee.setLastName("user-two");
Set accountsOfFirstEmployee = new HashSet();
accountsOfFirstEmployee.add(account1);
accountsOfFirstEmployee.add(account2);
Set accountsOfSecondEmployee = new HashSet();
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 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 getAccounts() {
return accounts;
}
public void setAccounts(Set accounts) {
this.accounts = accounts;
}
}
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">
com.mysql.jdbc.Driver
jdbc:mysql://localhost:3306/hibernatetest
XXXXXX
root
org.hibernate.dialect.MySQLDialect
true
create
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("[email protected]");
emp.setFirstName("demo");
emp.setLastName("user");
Set accounts = new HashSet();
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 (?, ?)