Hibernate关系映射小结

Hibernate关系映射小结

 

组建映射(User-Name)

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

<componentname=”name” class=”com.test.hibernate.domain.Name”>

   <property name=”initial”/>

   <property name=”first”/>

  <property name=”last”/>

</component>

当组建的属性不能和表中的字段简单对应的时候可以选择实现:

org.hibernate.usertype.UserType或

org.hibernate.usertype.CompositeUserType

例:

User类

privateInteger id;

privateName name;

privateString birth;

getter()和setter()…

Name类(必不可少的属性,单生成一个表太浪费,所以把Name里的字段都加到User表中)

privateString firstName;

privateString lastName;

getter()和setter()…

User.hbm.xml

<classname="User" table="user">

      <id name="id"column="id" unsaved-value="-1">

        <generatorclass="native"/>

      </id>

      <component name="name">

      <property name="firstName"column="first_name"/>

      <property name="lastName"column="last_name"/>

      </component>

      <property name="birth"column="birth"/>

   </class>

集合映射(set,list,array,bag,map)

<setname=”employees”>

   <keycolumn=”depart_id”/>

   <one-to-many class=”Employee”/>

   <!--<element type=”string” column=”name”/>-->

   <!—

      <composite-element class=”YourClass”>

        <property name=”prop1”/>

        <property name=”prop2”/>

      </composite>

-->

</set>

例:

<listname=”employees”>

   <key column=”depart_id”/>

   <!—表中有单独的整型列外表示list-index-->

   <list-index column=”order_column”/>

   <one-to-many class=”Employee”/>

</list>

<arrayname=”employees”>

   <key column=””depart_id/>

   <!—表中有单独的整型列表示list-index—>

   <list-index column=”order_column”/>

   <one-to-many class=”Employee”/>

</array>

<bagname=”employees” order-by=”id desc”>

   <key column=”depart_id”/>

   <one-to-many class=”Employee”/>

</bag>

<mapname=”employees”>

   <key column=”depart_id”/>

   <map_key type=”string” column=”name”/>

   <one-to-many class=”Employee”/>

</map>

这些集合类都是Hibernate实现的类和JAVA中的集合类不完全一样,set,list,map分别和JAVA中的Set,List,Map接口对应,bag映

射成JAVA的List;这些集合的使用和JAVA集合中对应的接口基本一致;在JAVA的实体类中集合只能定义成接口不能定义成具体类,因为集合会在运行时被替换成Hibernate的实现。

集合的简单实用原则:大部分情况下用set,需要保证集合中的顺序用list,想用java.util.List又不需要保证顺序用bag。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值