hibernate组件映射

来源:互联网 发布:淘宝网店授权书 编辑:程序博客网 时间:2024/06/01 21:43

hibernate组件映射也就是包含映射,关系犹如汽车(Car)与车轮(Wheel)

1、创建实体类Wheel.java

package cn.itcast.a;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;}}

2、创建实体类Car.java

package cn.itcast.a;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;}}

3、配置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="cn.itcast.a"><!--name为实体类的名称    table为表名  --><class name="Car" table="t_car"><!-- 主键字段 --><!-- name为实体类中的属性名 --><id name="id"><!-- native为自增长 --><generator class="native"></generator></id><!-- 其他字段 --><property name="name" length="20"></property><!--组件映射 --><component name="wheel"><property name="count"></property><property name="size"></property></component></class></hibernate-mapping>
4、配置hibernate.cfg.xml

<!DOCTYPE hibernate-configuration PUBLIC"-//Hibernate/Hibernate Configuration DTD 3.0//EN""http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"><hibernate-configuration><session-factory><property name="show_sql">true</property><!-- 数据库连接配置 --><property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property><property name="hibernate.connection.url">jdbc:mysql:///employee</property><property name="hibernate.connection.username">root</property><property name="hibernate.connection.password">123456</property><property name="dialect">org.hibernate.dialect.MySQL5Dialect</property><!-- 其他相关配置 --><!-- 显示hibernate在运行时执行的sql语句 --><property name="hibernate.show_sql">true</property><!-- 格式化sql --><property name="hibernate.format_sql">true</property><!-- 自动建表 --><property name="hibernate.hbm2ddl.auto">update</property><!-- 加载所有映射 --><mapping resource="cn/itcast/a/Car.hbm.xml"/></session-factory></hibernate-configuration>

5、创建测试类App.java

package cn.itcast.a;import static org.junit.Assert.*;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().buildSessionFactory();}@Testpublic void test() {Session session=sf.openSession();session.beginTransaction();Wheel wheel=new Wheel();wheel.setSize(40);wheel.setCount(4);Car car=new Car();car.setName("奔驰");car.setWheel(wheel);session.save(car);session.getTransaction();session.close();}}



原创粉丝点击