鍍金池/ 教程/ Java/ Hibernate通過one-to-one元素的一對一映射
Hibernate繼承映射
Hibernate每個(gè)子類一張表(使用XML文件)實(shí)例
Hibernate快速入門
Hibernate使用注釋
Hibernate使用xml文件的每個(gè)類層次一張表
Hibernate命名查詢
Hibernate每個(gè)層次類一張表(使用注釋)
Hibernate組件映射
Hibernate事務(wù)管理
Hibernate二級緩存
集合映射Set(使用xml文件)
Hibernate每個(gè)具體類一張表映射(使用XML)
集合映射中的映射列表(使用xml文件)
Hibernate使用Log4j日志記錄(使用properties文件)
Hibernate集合映射
集合Map映射(使用xml文件)
集合Set映射一對多(使用xml文件)
Hibernate查詢語言(HQL)
Hibernate入門程序
Hibernate標(biāo)準(zhǔn)查詢語言
Hibernate使用Log4j日志記錄(使用xml文件)
Hibernate教程
Hibernate體系結(jié)構(gòu)
Hibernate生成器類
Hibernate通過many-to-one元素的一對一映射
集合Map多對多映射(使用xml文件)
Web應(yīng)用程序使用Hibernate
Hibernate一對多映射列表實(shí)例(使用xml文件)
Hibernate通過one-to-one元素的一對一映射
Hibernate每個(gè)子類一張表(使用注釋)實(shí)例
集合映射中的映射包(使用xml文件)
通過Bag一對多映射示例(使用xml文件)
Hibernate緩存
Hibernate每個(gè)具體類一張表映射(使用注釋)

Hibernate通過one-to-one元素的一對一映射

正如我們在前面的例子中討論過的,在hibernate中執(zhí)行一對一映射有兩種方法:

  • 通過many-to-one元素
  • 通過one-to-one元素

這里,我們將通過one-to-one元素進(jìn)行一對一的映射。 在這種情況下,不會(huì)在主表中創(chuàng)建外鍵。

在這個(gè)例子中,一個(gè)員工只能有一個(gè)地址,一個(gè)地址只能屬于一個(gè)員工。 在這里使用雙向關(guān)聯(lián)。我們來看看持久化類。

1)一對一映射的持久類

有兩個(gè)持久化類Employee.javaAddress.java。 Employee類包含Address類引用,反之亦然。

創(chuàng)建一個(gè)名稱為:onetooneprimary 的java項(xiàng)目,其項(xiàng)目文件目錄結(jié)構(gòu)如下 -

文件:Employee.java

package com.yiibai;

public class Employee {
    private int employeeId;
    private String name, email;

    private Address address;

    public int getEmployeeId() {
        return employeeId;
    }

    public void setEmployeeId(int employeeId) {
        this.employeeId = employeeId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public Address getAddress() {
        return address;
    }

    public void setAddress(Address address) {
        this.address = address;
    }

}

文件:Address.java

package com.yiibai;

public class Address {
    private int addressId;
    private String addressLine1, city, state, country;
    private int pincode;
    private Employee employee;

    public int getAddressId() {
        return addressId;
    }

    public void setAddressId(int addressId) {
        this.addressId = addressId;
    }

    public String getAddressLine1() {
        return addressLine1;
    }

    public void setAddressLine1(String addressLine1) {
        this.addressLine1 = addressLine1;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getState() {
        return state;
    }

    public void setState(String state) {
        this.state = state;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    public int getPincode() {
        return pincode;
    }

    public void setPincode(int pincode) {
        this.pincode = pincode;
    }

    public Employee getEmployee() {
        return employee;
    }

    public void setEmployee(Employee employee) {
        this.employee = employee;
    }

}

2)持久化類映射文件

兩個(gè)映射文件分別是:employee.hbm.xmladdress.hbm.xml

文件:employee.hbm.xml

在這個(gè)映射文件中,我們在映射文件中使用one-to-one元素進(jìn)行一對一映射。

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
          "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
          "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
    <class name="com.yiibai.Employee" table="emp_2120">
        <id name="employeeId">
            <generator class="increment"></generator>
        </id>
        <property name="name"></property>
        <property name="email"></property>

        <one-to-one name="address" cascade="all"></one-to-one>
    </class>

</hibernate-mapping>

文件:address.hbm.xml

這是Address類的簡單映射文件。 但重要的是生成器(generator)類。 在這里,我們正在使用依賴于Employee類主鍵的外部generator類。

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
          "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
          "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
    <class name="com.yiibai.Address" table="address_2120">
        <id name="addressId">
            <generator class="foreign">
                <param name="property">employee</param>
            </generator>
        </id>
        <property name="addressLine1"></property>
        <property name="city"></property>
        <property name="state"></property>
        <property name="country"></property>

        <one-to-one name="employee" cascade="all"></one-to-one>
    </class>

</hibernate-mapping>

3)配置文件

此文件包含有關(guān)數(shù)據(jù)庫和映射文件的信息。
文件:hibernate.cfg.xml

<?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">

<!-- Generated by MyEclipse Hibernate Tools. -->
<hibernate-configuration>

    <session-factory>
        <property name="hbm2ddl.auto">update</property>

        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/test</property>
        <property name="connection.username">root</property>
        <property name="connection.password">123456</property>
        <property name="dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
        <property name="show_sql">true</property>

        <mapping resource="employee.hbm.xml" />
        <mapping resource="address.hbm.xml" />
    </session-factory>

</hibernate-configuration>

4)存儲(chǔ)和獲取數(shù)據(jù)的用戶類

文件:MainTest.java

package com.yiibai;

import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.*;
import org.hibernate.*;

public class MainTest {
    public static void main(String[] args) {
        // 在5.1.0版本匯總,hibernate則采用如下新方式獲?。?        // 1. 配置類型安全的準(zhǔn)服務(wù)注冊類,這是當(dāng)前應(yīng)用的單例對象,不作修改,所以聲明為final
        // 在configure("cfg/hibernate.cfg.xml")方法中,如果不指定資源路徑,默認(rèn)在類路徑下尋找名為hibernate.cfg.xml的文件
        final StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
                .configure("hibernate.cfg.xml").build();
        // 2. 根據(jù)服務(wù)注冊類創(chuàng)建一個(gè)元數(shù)據(jù)資源集,同時(shí)構(gòu)建元數(shù)據(jù)并生成應(yīng)用一般唯一的的session工廠
        SessionFactory sessionFactory = new MetadataSources(registry)
                .buildMetadata().buildSessionFactory();

        /**** 上面是配置準(zhǔn)備,下面開始我們的數(shù)據(jù)庫操作 ******/
        Session session = sessionFactory.openSession();// 從會(huì)話工廠獲取一個(gè)session
        // creating transaction object
        Transaction t = session.beginTransaction();

        Employee e1 = new Employee();
        e1.setName("蘇小明");
        e1.setEmail("xima.su@gmail.com");

        Address address1 = new Address();
        address1.setAddressLine1("G-1621, Renmin Road");
        address1.setCity("海口");
        address1.setState("海南");
        address1.setCountry("中國");
        address1.setPincode(572201);

        e1.setAddress(address1);
        address1.setEmployee(e1);

        session.persist(e1);
        t.commit();

        session.close();
        System.out.println("success");
    }
}

文件:FetchTest.java

package com.yiibai;

import java.util.Iterator;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;

public class FetchTest {
    public static void main(String[] args) {
        // 在5.1.0版本匯總,hibernate則采用如下新方式獲取:
        // 1. 配置類型安全的準(zhǔn)服務(wù)注冊類,這是當(dāng)前應(yīng)用的單例對象,不作修改,所以聲明為final
        // 在configure("cfg/hibernate.cfg.xml")方法中,如果不指定資源路徑,默認(rèn)在類路徑下尋找名為hibernate.cfg.xml的文件
        final StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
                .configure("hibernate.cfg.xml").build();
        // 2. 根據(jù)服務(wù)注冊類創(chuàng)建一個(gè)元數(shù)據(jù)資源集,同時(shí)構(gòu)建元數(shù)據(jù)并生成應(yīng)用一般唯一的的session工廠
        SessionFactory sessionFactory = new MetadataSources(registry)
                .buildMetadata().buildSessionFactory();

        /**** 上面是配置準(zhǔn)備,下面開始我們的數(shù)據(jù)庫操作 ******/
        Session session = sessionFactory.openSession();// 從會(huì)話工廠獲取一個(gè)session
        // creating transaction object
        Transaction t = session.beginTransaction();

        Query query = session.createQuery("from Employee e");
        List<Employee> list = query.list();

        Iterator<Employee> itr = list.iterator();
        while (itr.hasNext()) {
            Employee emp = itr.next();
            System.out.println(emp.getEmployeeId() + " " + emp.getName() + " "
                    + emp.getEmail());
            Address address = emp.getAddress();
            System.out.println(address.getAddressLine1() + " "
                    + address.getCity() + " " + address.getState() + " "
                    + address.getCountry());
        }

        session.close();
        System.out.println("success");
    }
}

5) 運(yùn)行示例

首先運(yùn)行 MainTest.java 來創(chuàng)建表并向表中插入一些數(shù)據(jù),然后運(yùn)行FetchTest.java來讀取上面插入的數(shù)據(jù)信息。

運(yùn)行 MainTest.java 得到的結(jié)果如下-

log4j:WARN No appenders could be found for logger (org.jboss.logging).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
Tue Mar 28 21:07:32 CST 2017 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Hibernate: select max(employeeId) from emp_2120
Hibernate: insert into emp_2120 (name, email, employeeId) values (?, ?, ?)
Hibernate: insert into address_2120 (addressLine1, city, state, country, addressId) values (?, ?, ?, ?, ?)
success

運(yùn)行 FetchTest.java 得到的結(jié)果如下-

log4j:WARN No appenders could be found for logger (org.jboss.logging).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
Tue Mar 28 21:07:57 CST 2017 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Hibernate: select employee0_.employeeId as employee1_1_, employee0_.name as name2_1_, employee0_.email as email3_1_ from emp_2120 employee0_
Hibernate: select address0_.addressId as addressI1_0_0_, address0_.addressLine1 as addressL2_0_0_, address0_.city as city3_0_0_, address0_.state as state4_0_0_, address0_.country as country5_0_0_, employee1_.employeeId as employee1_1_1_, employee1_.name as name2_1_1_, employee1_.email as email3_1_1_ from address_2120 address0_ left outer join emp_2120 employee1_ on address0_.addressId=employee1_.employeeId where address0_.addressId=?
Hibernate: select address0_.addressId as addressI1_0_0_, address0_.addressLine1 as addressL2_0_0_, address0_.city as city3_0_0_, address0_.state as state4_0_0_, address0_.country as country5_0_0_, employee1_.employeeId as employee1_1_1_, employee1_.name as name2_1_1_, employee1_.email as email3_1_1_ from address_2120 address0_ left outer join emp_2120 employee1_ on address0_.addressId=employee1_.employeeId where address0_.addressId=?
Hibernate: select address0_.addressId as addressI1_0_0_, address0_.addressLine1 as addressL2_0_0_, address0_.city as city3_0_0_, address0_.state as state4_0_0_, address0_.country as country5_0_0_, employee1_.employeeId as employee1_1_1_, employee1_.name as name2_1_1_, employee1_.email as email3_1_1_ from address_2120 address0_ left outer join emp_2120 employee1_ on address0_.addressId=employee1_.employeeId where address0_.addressId=?
1 Yiibai Su yiibai.su@gmail.com
G-1621, Renmin Road Haikou Hainan China
2 蘇小明 xima.su@gmail.com
G-1621, Renmin Road ???海南 中國
3 蘇小明 xima.su@gmail.com
G-1621, Renmin Road ???海南 中國
success