您的位置:首页 > 其它

Hibernate关系映射小结

2011-12-12 21:19 260 查看
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。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: