需求:汽车 和 轮胎,汽车包含轮胎;
一个类包含另一个类,这种关系叫 组合关系;
类组合关系的映射,也叫做 组件映射;
注意:具有组合关系的两个类,共同映射到一张表;
项目结构:
汽车实体类 Car.java:
package com.hibernate.component;
/**
* 汽车实体类
*/
public class Car {
private int id;
private String name;
private Wheel wheel; // 汽车包含轮胎,组合关系
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 Wheel getWheel() {
return wheel;
}
public void setWheel(Wheel wheel) {
this.wheel = wheel;
}
}
轮胎实体类 Wheel.java:
package com.hibernate.component;
/**
* 轮胎实体类
*/
public class Wheel {
private int size;
private int count;
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
}
映射配置 Car.hbm.xml:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.hibernate.component">
<class name="Car" table="t_car">
<!-- 主键映射 -->
<id name="id">
<generator class="native"/>
</id>
<!-- 普通字段映射 -->
<property name="name"/>
<!-- 组件映射 -->
<component name="wheel" class="Wheel">
<property name="size"/>
<property name="count"/>
</component>
</class>
</hibernate-mapping>
主配置 hibernate.cfg.xml:
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="connection.url">jdbc:mysql://localhost:3306/hib_demo</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">create</property> <!-- 自动建表 -->
</session-factory>
</hibernate-configuration>
测试程序 Demo.java:
package com.hibernate.component;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.junit.Test;
/**
* 组件映射:
* 一个类中包含了另一个类,这两个类就是组合关系;
* 例如:汽车 和 轮胎
*
* 类组合关系的映射,也叫 组件映射;
*
* 注意:具有组合关系的两个类 映射到同一张表中;
*/
public class Demo {
private static SessionFactory sessionFactory;
static {
sessionFactory = new Configuration()
.configure()
.addClass(Car.class) // 自动加载配置文件
.buildSessionFactory();
}
@Test
public void test(){
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
// 创建 轮胎对象
Wheel wheel = new Wheel();
wheel.setSize(30);
wheel.setCount(4);
// 创建 汽车对象
Car car = new Car();
car.setName("BMW");
car.setWheel(wheel);
// 保存
session.save(car);
transaction.commit();
session.close();
}
}