Hibernate 专题
专题目录
您的位置:java > Hibernate 专题 > Hibernate通过one-to-one元素的一对一映射
Hibernate通过one-to-one元素的一对一映射
作者:--    发布时间:2019-11-20 11:08:01

正如我们在前面的例子中讨论过的,在hibernate中执行一对一映射有两种方法:

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

这里,我们将通过one-to-one元素进行一对一的映射。 在这种情况下,不会在主表中创建外键。

在这个例子中,一个员工只能有一个地址,一个地址只能属于一个员工。 在这里使用双向关联。我们来看看持久化类。

1)一对一映射的持久类

有两个持久化类employee.javaaddress.javaemployee类包含address类引用,反之亦然。

创建一个名称为:onetooneprimary 的java项目,其项目文件目录结构如下 -

文件:employee.java

package com.h3;

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.h3;

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)持久化类映射文件

两个映射文件分别是: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 3.0//en"
          "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
    <class name="com.h3.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.h3.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)配置文件

此文件包含有关数据库和映射文件的信息。
文件: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)存储和获取数据的用户类

文件:maintest.java

package com.h3;

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. 配置类型安全的准服务注册类,这是当前应用的单例对象,不作修改,所以声明为final
        // 在configure("cfg/hibernate.cfg.xml")方法中,如果不指定资源路径,默认在类路径下寻找名为hibernate.cfg.xml的文件
        final standardserviceregistry registry = new standardserviceregistrybuilder()
                .configure("hibernate.cfg.xml").build();
        // 2. 根据服务注册类创建一个元数据资源集,同时构建元数据并生成应用一般唯一的的session工厂
        sessionfactory sessionfactory = new metadatasources(registry)
                .buildmetadata().buildsessionfactory();

        /**** 上面是配置准备,下面开始我们的数据库操作 ******/
        session session = sessionfactory.opensession();// 从会话工厂获取一个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.h3;

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. 配置类型安全的准服务注册类,这是当前应用的单例对象,不作修改,所以声明为final
        // 在configure("cfg/hibernate.cfg.xml")方法中,如果不指定资源路径,默认在类路径下寻找名为hibernate.cfg.xml的文件
        final standardserviceregistry registry = new standardserviceregistrybuilder()
                .configure("hibernate.cfg.xml").build();
        // 2. 根据服务注册类创建一个元数据资源集,同时构建元数据并生成应用一般唯一的的session工厂
        sessionfactory sessionfactory = new metadatasources(registry)
                .buildmetadata().buildsessionfactory();

        /**** 上面是配置准备,下面开始我们的数据库操作 ******/
        session session = sessionfactory.opensession();// 从会话工厂获取一个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) 运行示例

首先运行 maintest.java 来创建表并向表中插入一些数据,然后运行fetchtest.java来读取上面插入的数据信息。

运行 maintest.java 得到的结果如下-

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

运行 fetchtest.java 得到的结果如下-

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 h3 su h3.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

网站声明:
本站部分内容来自网络,如您发现本站内容
侵害到您的利益,请联系本站管理员处理。
联系站长
373515719@qq.com
关于本站:
编程参考手册