在组件映射中,我们将依赖对象映射作为组件。 组件是存储为值而不是实体引用的对象。 如果从属对象没有主键,则要使用此方法。 它用于组合(HAS-A
关系)的情况下,这就是为什么把它称为组件。 下面来看看看有HAS-A
关系的类。
Hibernate组件映射示例
创建一个Java项目:componentmapping
,项目的目录结构如下图所示 -
下面我们来看看每个文件中的代码。
文件:Address.java
package com.yiibai;
public class Address {
private String city, country;
private int pincode;
public Address() {
super();
// TODO Auto-generated constructor stub
}
public Address(String city, String country, int pincode) {
super();
this.city = city;
this.country = country;
this.pincode = pincode;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
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;
}
}
Java
文件:Employee.java
package com.yiibai;
public class Employee {
private int id;
private String name;
private Address address;
public Employee(String name, Address address) {
super();
this.name = name;
this.address = address;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
}
Java
文件:MainTest.java
package com.yiibai;
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 MainTest {
public static void main(String[] args) {
// 相对于3.x.x版本hibernate,我们在4.x.x采用如下方式获取我们的会话工厂:
// 1. 解析我们在hibernate.cfg.xml中的配置
// Configuration configuration = new Configuration().configure();
// 2. 创建服务注册类,进一步注册初始化我们配置文件中的属性
// ServiceRegistry serviceRegistry = new
// ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
// 3. 创建我们的数据库访问会话工厂
// SessionFactory sessionFactory =
// configuration.buildSessionFactory(serviceRegistry);
// 但在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 s = sessionFactory.openSession();// 从会话工厂获取一个session
// creating transaction object
Transaction t = s.beginTransaction();
Employee e1 = new Employee("Mina Sun", new Address("Haikou", "China", 221233));
Employee e2 = new Employee("Max Su", new Address("Haikou", "China",
224123));
s.save(e1);
s.save(e2);
t.commit();
s.close();
System.out.println("success...");
}
}
Java
文件: 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_cpmap">
<id name="id">
<generator class="increment"></generator>
</id>
<property name="name"></property>
<component name="address" class="com.yiibai.Address">
<property name="city"></property>
<property name="country"></property>
<property name="pincode"></property>
</component>
</class>
</hibernate-mapping>
XML
运行示例
下面我们来运行 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 22:09:16 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(id) from emp_cpmap
Hibernate: insert into emp_cpmap (name, city, country, pincode, id) values (?, ?, ?, ?, ?)
Hibernate: insert into emp_cpmap (name, city, country, pincode, id) values (?, ?, ?, ?, ?)
success...
Java
打开数据库表:emp_cpmap
,应该能到到插入的数据了。