在 Hibernate 中,有两种方式可以实现一对一的映射:

  • 通过 many-to-one 元素(使用 unique="true" 属性)
  • 通过 one-to-one 元素

在这里,我们将通过 one-to-one 元素

来实现一对一的映射。在这种情况下,主表中不会创建外键。

在这个示例中,一个员工可以有一个地址,一个地址也只属于一个员工。这里我们使用双向关联。让我们来看看持久类。

1) 一对一映射的持久类

这里有两个持久类 Employee.javaAddress.javaEmployee 类包含 Address 类的引用,反之亦然。

Employee.java

package cn.javatiku;

public class Employee {
    private int employeeId;
    private String name, email;
    private Address address;
    // setters and getters
}

Address.java

package cn.javatiku;

public class Address {
    private int addressId;
    private String addressLine1, city, state, country;
    private int pincode;
    private Employee employee;
    // setters and getters
}

2) 持久类的映射文件

两个映射文件分别是 employee.hbm.xmladdress.hbm.xml

employee.hbm.xml

在这个映射文件中,我们在两个映射文件中都使用了 one-to-one 元素来实现一对一映射。

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

<hibernate-mapping>
    <class name="cn.javatiku.Employee" table="emp212">
        <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 类的简单映射文件,但重要的是生成器类。这里我们使用了依赖于 Employee 类主键的 foreign 生成器类。

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

<hibernate-mapping>
    <class name="cn.javatiku.Address" table="address212">
        <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>
        <property name="pincode"></property>
        <one-to-one name="employee"></one-to-one>
    </class>
</hibernate-mapping>

3) 配置文件

此文件包含有关数据库和映射文件的信息。

hibernate.cfg.xml

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

<hibernate-configuration>
    <session-factory>
        <property name="hbm2ddl.auto">update</property>
        <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>
        <property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
        <property name="connection.username">system</property>
        <property name="connection.password">jtp</property>
        <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
        <mapping resource="employee.hbm.xml"/>
        <mapping resource="address.hbm.xml"/>
    </session-factory>
</hibernate-configuration>

4) 存储和获取数据的用户类

Store.java

package cn.javatiku;

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

public class Store {
    public static void main(String[] args) {
        StandardServiceRegistry ssr = new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build();
        Metadata meta = new MetadataSources(ssr).getMetadataBuilder().build();

        SessionFactory factory = meta.getSessionFactoryBuilder().build();
        Session session = factory.openSession();

        Transaction t = session.beginTransaction();

        Employee e1 = new Employee();
        e1.setName("Ravi Malik");
        e1.setEmail("ravi@gmail.com");

        Address address1 = new Address();
        address1.setAddressLine1("G-21,Lohia nagar");
        address1.setCity("Ghaziabad");
        address1.setState("UP");
        address1.setCountry("India");
        address1.setPincode(201301);

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

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

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

输出

10-1.png
10-2.png

Fetch.java

package cn.javatiku;

import java.util.*;
import javax.persistence.TypedQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;

public class Fetch {
    public static void main(String[] args) {
        StandardServiceRegistry ssr = new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build();
        Metadata meta = new MetadataSources(ssr).getMetadataBuilder().build();

        SessionFactory factory = meta.getSessionFactoryBuilder().build();
        Session session = factory.openSession();

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

        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() + " " + address.getPincode());
        }

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

输出

10-3.png

标签: Hibernate, Hibernate教程, Hibernate框架, Hibernate框架设计, Hibernate初级教程, Hibernate框架用法, Hibernate指南, Hibernate入门, Hibernate中级教程, Hibernate进阶教程, Hibernate高级教程, Hibernate下载