<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                合規國際互聯網加速 OSASE為企業客戶提供高速穩定SD-WAN國際加速解決方案。 廣告
                # Hiberate 一對多映射注解示例 > 原文: [https://howtodoinjava.com/hibernate/hibernate-one-to-many-mapping-using-annotations/](https://howtodoinjava.com/hibernate/hibernate-one-to-many-mapping-using-annotations/) **在兩個實體之間進行 Hiberate 的一對多映射**,其中第一個實體可以與多個第二個實體實例有關系,而第二個實體只能與第一個實體的一個實例關聯。 其 **1 與 N** 的關系。 例如,在任何公司中,一名員工可以注冊多個銀行帳戶,但是一個銀行帳戶將與一個且只有一個雇員相關聯。 在此 [Hiberate](https://howtodoinjava.com/hibernate-tutorials/) 一對多映射注解示例中,我們將學習使用 Hiberate 在數據庫中進行此類映射。 ```java Table of Contents When to use one to many mapping Hibernate one to many mapping solutions 1\. Hibernate one to many mapping with foreign key association 2\. Hibernate one to many mapping with join table ``` ## 何時使用一對多映射 使用一個映射來創建實體或對象之間的`1..N`關系。 例如,我們必須編寫兩個實體,即`EmployeeEntity`和`AccountEntity`,以便多個帳戶可以與一個雇員相關聯,但是一個帳戶不能在兩個或多個雇員之間共享。 ## Hiberate 一對多映射解決方案 這個問題可以用兩種不同的方式解決。 1. 一種是在帳戶表中具有**外鍵列**,即`EMPLOYEE_ID`。 該列將引用`Employee`表的主鍵。 這樣,沒有兩個帳戶可以與多個員工關聯。 顯然,為了執行此限制,帳號必須唯一。 2. 第二種方法是有一個通用的**連接表**`EMPLOYEE_ACCOUNT`。 該表將具有兩列,即`EMP_ID`將是引用`EMPLOYEE`表中主鍵的外鍵,而`ACCOUNT_ID`將會是引用`ACCOUNT`表主鍵的外鍵。 ## 1\. 使用外鍵關聯 Hiberate 一對多映射 在這種方法中,**這兩個實體將負責建立關系**并維護它。 `EmployeeEntity`應該聲明這種關系是一對多的,`AccountEntity`應該聲明它的關系是多對一的。 #### 1.1 設計一對多映射關系 首先讓我們看一下架構設計。 ![one To Many association in hiberate using foreign key](https://img.kancloud.cn/eb/2e/eb2eeb52042407b99811db77abc5231a_486x160.png "one To Many association in hiberate using foreign key") #### 1.2 實體類 編寫實體類。 ```java 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; //Getters and setters } ``` 編寫`AccountEntity.java`。 ```java 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; //Getters and setters } ``` #### 1.3 演示 ```java 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(); } } ``` 程序輸出: ```java 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=? ``` ## 2\. 使用連接表 Hiberate 一對多映射 此方法使用**連接表**存儲帳戶和員工實體之間的關聯。 `@JoinTable`注解已用于建立此關聯。 #### 2.1 設計 讓我們看看數據庫架構如何: ![one To Many association in hiberate using join table](https://img.kancloud.cn/e9/1e/e91ebff6ee006abc066abd099741b00f_668x160.png "one To Many association in hiberate using join table") Hibernate 中的使用連接表的一對多關聯 #### 2.2 實體類 ```java 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; //Getters and setters } ``` ```java 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; //Getters and setters } ``` #### 2.3 Hiberate 配置 **我們已經為運行時提供了兩個實體,我們必須將它們添加到`hibernate.cfg.xml`文件中。 請注意,只能在配置文件中配置一組實體,否則可能會發生意外結果。** ```java < ?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> ``` #### 2.4 演示 現在,該測試代碼了。 我已經編寫了以下代碼來測試上述實體。 ```java 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(); } } ``` 程序輸出: ```java 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 (?, ?) ``` [下載源碼](https://docs.google.com/open?id=0B7yo2HclmjI4b2dvbk40cUtvSzQ "hibernate-test-project-one-to-many-association") 在這個**使用列表的** Hiberate 一對多映射注解示例的過程中,我們學習了使用外鍵關聯和連接表技術在兩個實體之間創建`1..N`關系。 學習愉快! 閱讀更多: [Hiberate 一對一映射注解示例](https://howtodoinjava.com/hibernate/hibernate-one-to-one-mapping-using-annotations/) [Hiberate 多對多映射注解示例](https://howtodoinjava.com/hibernate/hibernate-many-to-many-mapping-using-annotations/)
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看