zoukankan      html  css  js  c++  java
  • Hibernate的集合映射与sort、order-by属性

    【Hibernate】Hibernate的集合映射与sort、order-by属性

    常用集合Set、List、Map,相信大家都很熟悉,面试中也会经常问。Set和List都继承了Collection接口,Set是无序不可重复的,不可以存储相同的元素;而Lsit是顺序存储的,可存储重复元素。Map不是继承Collection的,Map提供key到value的映射,Map也是不可重复的(key不可重复),一个Map中不能包含相同的key,每个key只能映射一个value。

    持久化类的属性是集合时,要把它们存到数据库中,需要增设数据库表来完成映射工作。例如一个学生的教育背景可能不止一个,这个时候持久化类的属性是集合,这个时候数据库就需要再提供一张数据库表来存储。

    由上图可以看出,集合的映射应该怎么写了。集合的映射大致一样,我们用Set的映射来详细说明。

    <set name="education" table="student_education" order-by=" education DESC">
    			<key column="student_id"></key>
    			<element type="string" column="education"></element>
    </set>
    

    name属性是指对象的集合属性名,table属性是指集合表(数据库表)的名称,key子元素是指集合外键的列名,element子元素用来存放集合元素的列的信息,order-by属性是指查询数据库时指定order by 子句,这是在数据库中的排序。对于Set的排序,还有另外一个属性sort,它是在内存中排序的,默认是unsorted,sort还有其它两个值:natural和comparatorClass,当使用sort属性时,要求使用的是可以排序的Set,例如TreeSet等。

    List的映射:

    <list name="education" table="student_education">
    			<key column="student_id"></key>
    			<list-index column="list_id"></list-index>
    			<element type="string" column="education"></element>
    </list>
    

    List的映射与Set很相似,多了一个list-index子元素,是指定List的索引对应于集合表中的哪个字段。因为List是有序的,可以通过索引来取值。也正因为有序,所以不可以使用sort属性进行排序。

    Map的映射:

    <p><map name="education" table="student_education"></p><p>                     <keycolumn="student_id"></key></p><p>                     <map-keytype="string" column="map_key"></map-key></p><p>                     <element type="string"column="education"></element></p><p></map></p>

    map-key子元素是指定Map的key值对应集合表中的哪个字段。

    除了这3个常用的集合的映射,hibernate还提供了另外两种集合的映射:数组和Bag。数组性质跟List相似,但是数组的长度不可变;Bag也与List相似,但是它是无序可重复的。因此数组的映射与List基本一样:

    <array name="education" table="student_education">
    			<key column="student_id"></key>
    			<list-index column="list_id"></list-index>
    			<element type="string" column="education"></element>
    </array>
    

    Bag的映射就比List少一个list-index子元素:

    <bag name="education" table="student_education">
                         <keycolumn="student_id"></key>
                         <elementtype="string" column="education"></element>
    </bag>

    注意:

    使用集合属性时,一定要使用接口,而不能声明为具体实现类。因为经过session操作后,集合就变成hibernate自己的集合实现类。

    最好再整理一次关于sort也order-by属性的使用:

    由于Set与Map都是无序的,所以我们可以使用sort或者order-by属性对它们进行排序。sort是在内存中排序的,要求使用的Set与Map也是可排序的。这种排序方法不建议使用,使用较多的,排序也比较快的是使用order-by属性,直接在数据库中排序。

  • 相关阅读:
    Windows开启telnet服务 + 连接失败处理
    注册表比较工具
    wmic命令
    python netifaces模块
    【转】wireshark基本用法及过虑规则
    设置Intel网卡以抓取报文的vlan tag
    【转】 中兴OLT-C300常用命令
    Iris分类以及数组reshape想到的
    关于plot画图的原理
    Python的rand vs randn以及linspace
  • 原文地址:https://www.cnblogs.com/hoobey/p/5967545.html
Copyright © 2011-2022 走看看