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

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

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

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

1)一对一映射的持久类

有两个持久化类Employee.javaAddress.java。 Employee类包含Address类引用,反之亦然。

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

文件: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;
} }
Java

文件: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;
} }
Java

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.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>
XML

文件: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>
XML

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>
XML

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

文件: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. 配置类型安全的准服务注册类,这是当前应用的单例对象,不作修改,所以声明为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");
}
}
Java

文件: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. 配置类型安全的准服务注册类,这是当前应用的单例对象,不作修改,所以声明为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");
}
}
Java

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

Hibernate通过one-to-one元素的一对一映射的更多相关文章

  1. Hibernate通过many-to-one元素的一对一映射

    在hibernate中我们可以通过两种方式来执行一对一映射: 通过many-to-one元素标签 通过one-to-one元素标签 在这里,我们将通过多对一的many-to-one元素进行一对一的映射 ...

  2. Hibernate中的一对一映射关系

    Hibernate中的一对一映射关系有两种实现方法(单向一对一,和双向一对一)(一对一关系:例如一个department只能有一个manager) 单向和双向有什么区别呢??例如若是单向一对一,比如在 ...

  3. Hibernate表关系映射之一对一映射

    一.数据表的映射关系 在数据库领域中,数据表和数据表之间关系一般可以分为如下几种: 一对一:比如公民和身份证的关系,一个人只有一张身份证,同时每张身份证也仅仅对应一个人! 一对多:比如客户和订单之间的 ...

  4. Hibernate的一对一映射

    一.创建Java工程,新建Lib文件夹,加入Hibernate和数据库(如MySql.Oracle.SqlServer等)的Jar包,创建 hibernate.cfg.xml 文件,并配置,配置项如下 ...

  5. hibernate笔记--基于主键的单(双)向的一对一映射关系

    上一节介绍的基于外键的一对一映射关系中,在Person表中有一个外键列idCard_id,对应的idCard表的主键id,至于基于主键的一对一映射关系,就是指Person表中抛弃了idcard_id这 ...

  6. hibernate笔记--基于外键的单(双)向的一对一映射关系

    假设我们有两张表,人员信息表Person,和身份信息表IdCard,我们知道每个人只有一个身份证号,所以这里的Person和IdCard表是一一对应的,也就是一对一的映射关系,基于外键的单向一对一映射 ...

  7. Hibernate一对一映射关联

    Hibernate提供了两种一对一映射关联关系的方式: 1)按照外键映射 2)按照主键映射 下面以员工账号表和员工档案表(员工账号和档案表之间是一对一的关系)为例,介绍这两种映射关系,并使用这两种 映 ...

  8. Hibernate中的一对一映射

    1.需求 用户和身份证是一一对应的关系. 有两种对应方式: 用户id作为身份证表的外键,身份证号作为主键: 用户id作为身份证表的主键: 2.实体Bean设计 User: public class U ...

  9. 【Hibernate 3】一对一映射配置

    一.一对一映射简介 一对一关联映射有两种实现策略: 第一种:主键关联,即让两个对象具有相同的主键值,以表明它们之间的一一对应的关系:数据库表不会有额外的字段来维护它们之间的关系,仅通过表的主键来关联 ...

随机推荐

  1. Shell实现多级菜单系统安装维护脚本实例分享

    Shell实现多级菜单系统安装维护脚本实例分享 这篇文章主要介绍了Shell实现多级菜单系统安装维护脚本实例分享,本文脚本用多级菜单实现管理WEB服务器.Mysql服务器.Nginx服器等,需要的朋友 ...

  2. django admin富文本编辑kindeditor

    最近在做django项目,需要在后台管理系统加入富文本编辑 其实加入富文本编辑很简单,就是导入几个编辑器的js脚本到admin页面内,下面说说怎么做 第一步,下载想要的富文本编辑器如kindedito ...

  3. webpack配置:增加babel支持、打包后调试

    一.babel支持 Babel其实是几个模块化的包,其核心功能位于称为babel-core的npm包中,webpack可以把其不同的包整合在一起使用,对于每一个你需要的功能或拓展,你都需要安装单独的包 ...

  4. linux 输出重定向 何时会写文件

    linux 输出重定向 何时会写文件 测试到了8K才会进行flush:

  5. Linux下SVN服务器搭建(CentOS+Subversion)--转

    svn(subversion)是近年来崛起的版本管理工具,是CVS的接班人.目前,绝大多数开源软件都使用svn作为代码版本管理软件.svn 服务器有2种运行方式:独立服务器和借助apache等web服 ...

  6. [TypeScript] Export public types from your library

    If you're a library author, it's useful to expose your public types as interfaces, to allow your con ...

  7. PostgreSQL学习资料

    我的PostgreSQL学习笔记:http://note.youdao.com/share/?id=2e882717fc3850be9af503fcc0dfe7d0&type=notebook ...

  8. Android短信发送器(2)

    在上一篇的<Android短信发送器>当中.发送功能并不完好.当发送内容超过限定字数时,短信就会发送失败,此时就须要推断内容是否超过限制,假设不超过限制.就直接发送,反之.则对其进行处理再 ...

  9. selenium从入门到应用 - 8,selenium+testNG实现多线程的并发测试

    本系列所有代码 https://github.com/zhangting85/simpleWebtest本文将介绍一个Java+TestNG+Maven+Selenium的web自动化测试脚本环境下s ...

  10. HDU 4287 Intelligent IME(map运用)

    转载请注明出处:http://blog.csdn.net/u012860063 题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4287 Intellig ...