读书人

Java乔晓松-Hibernate聚合映射

发布时间: 2013-01-02 13:08:44 作者: rapoo

Java乔晓松-Hibernate集合映射

集合映射:set list bag map

<set>元素:可以映射java.util.Set接口的属性,元素没有顺序且不允许重复。

<list>元素:可以映射java.util.List接口的属性,有顺序,需要在集合属性对应的表中用一个额外的索引保存每个元素的位置。

<bag> <idbag>元素:可以映射java.util.Collection接口的属性,元素可重复,但不保存顺序。

<map>元素:可以映射java.util.Map接口的属性,元素以键/值对的形式保存,也是无序的。

<primitive-array> <array>:可以映射数组元素。

<set>元素

private Set<String> hobbies;

<set name=“hobbies” table=“student_hobby”>

<key column=“student_id”/>

<element type=“string” column=“hobby_name” not-null=“true”/>

</set>

<list>元素

private List<String> hobbies;

<list name=“hobbies” table=“student_hobby”>

<key column=“student_id”/>

<list-index column=“posistion”/>

<element type=“string” column=“hobby_name” not-null=“true”/>

</list>

<bag>元素

private Collection<String> hobbies;

<bag name=“hobbies” table=“student_hobby”>

<key column=“student_id”/>

<element type=“string” column=“hobby_name” not-null=“true”/>

</bag>

<map>元素

private Map<Long String> hobbies;

<map name=“hobbies” table=“student_hobby”>

<key column=“student_id”>

<map-key column=“hobby_id” type=“long”/>

<element type=“string” column=“hobby_name” not-null=“true”/>

</map>

集合映射

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

<set name=”employees” >

<keycolumn=”depart_id”/>

<one-to-manyclass=”Employee”/>

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

<!--

<composite-elementclass=”YourClass”>

<propertyname=”prop1”/>

<propertyname=”prop2”/>

</composite>

-->

</set>

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

<list name=”employees” >

<keycolumn=”depart_id”/>

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

<list-indexcolumn=”order_column”/>

<one-to-manyclass=”Employee”/>

</list>

<array name=”employees” >

<keycolumn=”depart_id”/>

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

<list-indexcolumn=”order_column”/>

<one-to-manyclass=”Employee”/>

</array>

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

<bag name="employees "order-by="id desc">

<keycolumn=”depart_id”/>

<one-to-manyclass=”Employee”/>

</bag>

<map name="employees ">

<keycolumn=”depart_id”/>

<map-keytype="string" column="name"/>

<one-to-manyclass=”Employee”/>

</map>

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

这些集合类都是Hibernate实现的类和JAVA中的集合类不完全一样,set,list,map分别和JAVA中的Set,List,Map接口对应,bag映射成JAVA的List;这些集合的使用和JAVA集合中对应的接口基本一致;在JAVA的实体类中集合只能定义成接口不能定义成具体类, 因为集合会在运行时被替换成Hibernate的实现。

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

cascade和inverse (Employee Department)

Casade用来说明当对主对象进行某种操作时是否对其关联的从对象也作类似的操作,常用的cascade:

none,all,save-update,delete, lock,refresh,evict,replicate,persist,

merge,delete-orphan(one-to-many)。一般对many-to-one,many-to-many不设置级联,在<one-to-one>和<one-to-many>中设置级联。

inverse表“是否放弃维护关联关系”(在Java里两个对象产生关联时,对数据库表的影响),在one-to-many和many-to-many的集合定义中使用,inverse=”true”表示该对象不维护关联关系;该属性的值一般在使用有序集合时设置成false(注意hibernate的缺省值是false)。

one-to-many维护关联关系就是更新外键。many-to-many维护关联关系就是在中间表增减记录。

注: 配置成one-to-one的对象不维护关联关系

读书人网 >Web前端

热点推荐