您的位置:首页 > 数据库

组件(Component)映射

2017-08-01 11:30 295 查看
在hibernate中,Component是某个实体的逻辑组成部分,它与实体的根本区别是没有oid(对象标识符),Component是一个被包含的对象,它作为值类型被持久化,而非一个实体。

在hibernate中Component映射采用<component>标签即可。

示例:

1、类Teacher

public class Teacher {
private int id;
private String name;
private String sex;
private Address address;
//省略get/set方法
}2、类Teacher的组件Address
public class Address {
private String addr1;
private String addr2;
private String addr3;
//省略get/set
}3、Teacher.hbm.xml配置
<hibernate-mapping package="com.test.pojo">
<class name="Teacher">
<id name="id">
<generator class="native"></generator>
</id>
<property name="name" />
<property name="sex" />
<!-- 组件 -->
<component name="address" class="Address">
<property name="addr1" />
<property name="addr2" />
<property name="addr3" />
</component>
</class>
</hibernate-mapping>4、HibernateUtil
public class HibernateUtil {
private static Configuration cfg=null;
private static SessionFactory factory=null;
private static Session session=null;
static{
cfg=new Configuration().configure();
factory=cfg.buildSessionFactory(new StandardServiceRegistryBuilder()
.applySettings(cfg.getProperties()).build());
}
public static Session getSession(){
if(factory!=null)
return factory.openSession();
factory=cfg.buildSessionFactory(new StandardServiceRegistryBuilder()
.applySettings(cfg.getProperties()).build());
return factory.openSession();
}
public static void closeSession(){
if(session!=null && session.isOpen())
session.close();
}
}
5、测试

public class HibernateTest {
@Test
public void testCreateDB(){
Configuration cfg=new Configuration().configure();
SchemaExport se=new SchemaExport(cfg);
//第一个参数表示是否生成ddl脚本,第二个参数表示是否执行到数据库中
se.create(true, true);
}
/**
* 保存数据
*/
@Test
public void save(){
Session session=null;
Transaction tx=null;
try{
session=HibernateUtil.getSession();
tx=session.beginTransaction();
Teacher t=new Teacher();
t.setName("张三");
t.setSex("男");
Address address=new Address();
address.setAddr1("丰台");
address.setAddr2("朝阳");
address.setAddr3("海淀");
t.setAddress(address);
session.save(t);
tx.commit();
}catch(Exception e){
if(tx!=null)
tx.rollback();
e.printStackTrace();
}finally{
HibernateUtil.closeSession();
}
}
}执行testCreateDB控制台打印信息如下:



执行save控制台打印信息如下:



数据库表结构如下:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息