`
txidol
  • 浏览: 52220 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

Hibernate学习笔记(七)【映射值类型集合】

阅读更多

Set

 

<hibernate-mapping >
  <class name="mypack.Monkey" table="MONKEYS" >
    <id name="id" type="long" column="ID">
      <generator class="increment"/>
    </id>
    <property name="name" type="string" >
        <column name="NAME" length="15" />
    </property>
   <set   name="images"   table="IMAGES"    lazy="true" >
        <key column="MONKEY_ID" />
       <element column="FILENAME" type="string"  not-null="true"/>
   </set>   
  </class> 
</hibernate-mapping>

说明:

1.值类型,就说Image类就行String类型一样当值搞了,一切受包含它的类控制

2.他是在数据库中有表的,并且可延时加载(默认),数据库有ID 和MONKEY_ID

3.elemet,你懂的,实体类可没这个。

4.Set是hibernate里的Persistent类,Hash的 也就是无序的

 

Bag

 

<hibernate-mapping >
  <class name="mypack.Monkey" table="MONKEYS" >
    <id name="id" type="long" column="ID">
      <generator class="increment"/>
    </id>
    <property name="name" type="string" >
        <column name="NAME" length="15" />
    </property>
   <idbag   name="images"   table="IMAGES"    lazy="true">
        <collection-id type="long" column="ID">
           <generator class="increment"/>
        </collection-id>
        <key column="MONKEY_ID" />
        <element column="FILENAME" type="string"  not-null="true"/>
   </idbag>   
  </class>
</hibernate-mapping>

说明:

和上一个唯一的区别是他可以放相同的元素,上面那个是Set你懂的

 

List

 

   <list   name="images"   table="IMAGES"    lazy="true">
        <key column="MONKEY_ID" />
        <list-index column="POSITION" />
        <element column="FILENAME" type="string"  not-null="true"/>
   </list>  

说明:

1.它的数据库没有ID主键,多了个POSITIOM的字段,显然他可以排序;Image类中是没有position属性的。存是按放入的先后顺序来的

2.对了Bag和List 在Monkey中都是包含了一个List的图片集合,但是BAG无序,List存的时候哪个先存,拿的时候可以get(0)这样取。

 

Map

 

   <map   name="images"   table="IMAGES"    lazy="true">
        <key column="MONKEY_ID" />
        <map-key column="IMAGE_NAME" type="string"/>
        <element column="FILENAME" type="string"  not-null="true"/>
   </map>   

说明:

1.数据库有个ID和MONKEY_ID,组成联合主键

2.处理的时候 得到一个Map images=monkey.getImages() 他有Set keys = images.keySet();显然这个是我们IMAGE_NAME 无序

 

这么多无序了,我们怎么对集合排序呢?有2种策略:

1.在数据库查的时候排好序,这个只有List不支持,因为他完全由自己排序

示例: <set   name="images"   table="IMAGES"    lazy="true" order-by="lower(FILENAME) desc">
              <key column="MONKEY_ID" />
              <element column="FILENAME" type="string"  not-null="true"/>
       </set>   

说明是的每次查的时候在屁股后面加了双引号里的语句

 

2.也可以内存排序,其实就是查出来后,用Comparator给查出来的集合排了一把

示例: <set   name="images"   table="IMAGES"    lazy="true" sort=mypack.selfCpmparator">
              <key column="MONKEY_ID" />
              <element column="FILENAME" type="string"  not-null="true"/>
       </set>   

两个都用,纯粹傻逼,当然肯定是sort有效果,但愿Hibernate不会去排序查

 

排序的时候,集合的实现类就可以用TreeSet TreeMap叻,完全排序完成。如Monkey类里面有成员 private Map images=new TreeMap();

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics