分享

6.1.6 Sorted and ordered collections (1)- sorted collections, SortedMap,SortedSet

 moonboat 2009-02-12
6.1.6 Sorted  collections
In a startling abuse of the English language, the words sorted and ordered mean different
things when it comes to Hibernate persistent collections. A sorted collection is
sorted in memory using a Java comparator. An ordered collection is ordered at the
database level using an SQL query with an order by clause.
Let’s make the map of images a sorted map. First, you need to change the initialization
of the Java property to a java.util.TreeMap and switch to the
java.util.SortedMap interface:
private SortedMap images = new TreeMap();

public SortedMap getImages() {
      return this.images;
}
public void setImages(SortedMap images) {
      this.images = images;
}

Hibernate handles this collection accordingly, if you map it as sorted:
 
<map name="images" table="ITEM_IMAGE" sort="natural">
      <key column="ITEM_ID"/>
      <map-key column="IMAGENAME" type="string"/>
      <element type="string" column="FILENAME" not-null="true"/>
</map>
By specifying sort="natural", you tell Hibernate to use a SortedMap and to sort
the image names according to the compareTo() method of java.lang.String. If
you need some other sort algorithm (for example, reverse alphabetical order),
you may specify the name of a class that implements java.util.Comparator in
the sort attribute. For example:
<map name="images" table="ITEM_IMAGE" sort="auction.util.comparator.ReverseStringComparator">
      <key column="ITEM_ID"/>
      <map-key column="IMAGENAME" type="string"/>
      <element type="string" column="FILENAME" not-null="true"/>
</map>
A java.util.SortedSet (with a java.util.TreeSet implementation) is mapped
like this:
<set name="images" table="ITEM_IMAGE" sort="natural">
      <key column="ITEM_ID"/>
      <element type="string" column="FILENAME" not-null="true"/>
</set>
Bags may not be sorted (there is no TreeBag, unfortunately), nor may lists; the
order of list elements is defined by the list index.

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多