在hibernate中我们可以通过两种方式来执行一对一映射:
- 通过many-to-one元素标签
- 通过one-to-one元素标签
在这里,我们将通过多对一的many-to-one元素进行一对一的映射。 在这种情况下,在主表中创建外键。
在这个例子中,一个员工只能有一个地址,一个地址只能属于一个员工。 在这里使用双向关联。 我们来看看持久化类。
一对一映射示例
创建一个名称为:onetoonemappingforeign的java项目,其项目文件目录结构如下 -
1)一对一映射的持久类
有两个持久化类Employee.java和Address.java。Employee类包含Address类引用,反之亦然(Address类包含Employee类引用)。下面我们来看看它们的代码实现。
文件: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)持久化类映射文件
两个映射文件是employee.hbm.xml和address.hbm.xml。 在employee.hbm.xml映射文件中,many-to-one元素标签使用unique =“true”属性进行一对一映射。
文件:employee.hbm.xml
<?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_2110">
<id name="employeeId">
<generator class="increment"></generator>
</id>
<property name="name"></property>
<property name="email"></property> <many-to-one name="address" unique="true" cascade="all"></many-to-one>
</class> </hibernate-mapping>
文件:address.hbm.xml
这是Address类的简单映射文件。
<?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_2110">
<id name="addressId">
<generator class="increment"></generator>
</id>
<property name="addressLine1"></property>
<property name="city"></property>
<property name="state"></property>
<property name="country"></property> </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.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("Max Su");
e1.setEmail("maxsu@gmail.com"); Address address1 = new Address();
address1.setAddressLine1("1688, RenMin Road");
address1.setCity("Haikou");
address1.setState("Hainan");
address1.setCountry("China");
address1.setPincode(201301); 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.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 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");
}
}
运行测试
首先运行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.
Mon Mar 27 23:24:53 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: create table address_2110 (addressId integer not null, addressLine1 varchar(255), city varchar(255), state varchar(255), country varchar(255), primary key (addressId)) engine=InnoDB
Hibernate: create table emp_2110 (employeeId integer not null, name varchar(255), email varchar(255), address integer, primary key (employeeId)) engine=InnoDB
Hibernate: alter table emp_2110 drop index UK_o59xt2yukiefdxhv7bx8u0o3a
Hibernate: alter table emp_2110 add constraint UK_o59xt2yukiefdxhv7bx8u0o3a unique (address)
Hibernate: alter table emp_2110 add constraint FKplaygd7gpfedy290hg81wi1ba foreign key (address) references address_2110 (addressId)
Hibernate: select max(employeeId) from emp_2110
Hibernate: select max(addressId) from address_2110
Hibernate: insert into address_2110 (addressLine1, city, state, country, addressId) values (?, ?, ?, ?, ?)
Hibernate: insert into emp_2110 (name, email, address, employeeId) values (?, ?, ?, ?)
success