标签:hibernate
不相信自己的人 连努力的价值都没有。 |
类组合关系的映射,也叫做组件映射!
注意:组件类和被包含的组件类,共同映射到一张表!
需求: 汽车与车轮
生成的表:主键、汽车名称、轮胎大小、轮胎数量
Wheel.java
package com.rk.hibernate.m_component; public class Wheel { private int count; private int size; 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; } }
Car.java
package com.rk.hibernate.m_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; } }
Car.hbm.xml
<?xml version="1.0" encoding="UTF-8"?> <!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.rk.hibernate.m_component" auto-import="true"> <class name="Car" table="T_Cars"> <id name="id" column="carId"> <generator class="native"></generator> </id> <property name="name" column="carName"></property> <!-- 组件映射 --> <component name="wheel"> <property name="size" column="wheelSize"></property> <property name="count" column="wheelCount"></property> </component> </class> </hibernate-mapping>
App.java
package com.rk.hibernate.m_component; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; 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(80); wheel.setCount(4); // 汽车 Car car = new Car(); car.setName("BMW"); car.setWheel(wheel); // 保存 session.save(car); session.getTransaction().commit(); session.close(); } }
生成的数据表
标签:hibernate
原文地址:http://lsieun.blog.51cto.com/9210464/1826510