一,概述
1)一个类中包含另一个类(车与轮子),这两个类就是组合关系.
2)类组合关系的映射,也称为组件映射.
3)组件类和被包含的组件类,共同映射到同一张表.
4)需求:车与轮子.
二,JavaBean设计
1)Car.java
package com.bighuan.d_component;
public class Car {
private int id;
private String name;
// 车轮
private Wheel wheel;
public Car(){
}
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;
}
}
2)Wheel.java
package com.bighuan.d_component;
// 轮子
public class Wheel {
private int count;
private int size;
public Wheel(){
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
}
三,映射文件
1)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.bighuan.d_component">
<class name="Car" table="t_car">
<id name="id">
<generator class="native"></generator>
</id>
<property name="name" length="20"></property>
<!-- 组件映射 -->
<component name="wheel">
<property name="size"></property>
<property name="count"></property>
</component>
</class>
</hibernate-mapping>
2)测试
package com.bighuan.d_component;
import org.hibernate.Hibernate;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.classic.Session;
import org.junit.Test;
public class App {
private static SessionFactory sf;
static {
sf = new Configuration()
.configure()
.addClass(Car.class)
.buildSessionFactory();
}
@Test
public void testSave() {
Session session = sf.openSession();
session.beginTransaction();
// 轮子
Wheel wheel = new Wheel();
wheel.setSize(38);
wheel.setCount(4);
// 车
Car car = new Car();
car.setName("BMW");
car.setWheel(wheel);
// 保存
session.save(car);
session.getTransaction().commit();
session.close();
}
}
执行测试方法,数据库多了一张t_car表:id,name,size,coun,成功将数据插入了数据库.