hibernate学习之第八篇

本文介绍Hibernate中组件(Component)的概念及应用,通过示例展示如何将复杂类型属性映射为数据库表字段,适用于希望了解单表对象细分及提高代码可维护性的开发者。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

组件映射

关联的属性是个复杂类型的持久化类,但不是实体即:数据库中没有表与该属性对应,但该类的属性要持久保存的。

对于单表的对象细分,在hibernate中可借助Component节点的定义完成。
何谓Component?从名字上来看,既然称之为组件,则其必然是从属于某个整体的一个组成部分。在hibernate语义中,我们将某个实体对象中的一个逻辑 组成成为Component。

component与实体对象的根本差别,就在于Component没有标识,它作为一个逻辑组成,完全从属于实体对象。
示例:

 <component name="userName">
            <property name="firstName" column="first_name"></property>
            <property name="lastName" column="last_name"></property>
 </component>

 

user类代码如下:

public class User{

    private int id;
    private Name userName;
    private Date birthday;

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public Name getUserName() {
        return userName;
    }

    public void setUserName(Name userName) {
        this.userName = userName;
    }
}

 

Name类源代码如下:

package hibernatetest;

public class Name {
private String firstName;

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
    private String lastName;
}

 

user.hbm.xml配置信息如下:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="hibernatetest">
    <class name="User" table="`user`">
        <id name="id">
            <generator class="hilo"/>
        </id>
        <component name="userName">
            <property name="firstName" column="first_name"></property>
            <property name="lastName" column="last_name"></property>
        </component>

        <property name="birthday"/>
    </class>
</hibernate-mapping>
不需要对name类单独的写映射文件,直接包含到了user映射文件中去。

对象中的属性比较复杂,可以将其独立出来处理。
1,可以用两张表来实现一对一的映射。
2,如果想把信息保存到同一张表中,则可以使用component。


当组件的属性不能和表中的字段简单对应的时候可以选择使用用户自定义类型org.hibernate.usertype.UserType或org.hibernate.usertype.CompositeUserType

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值