6.1.6 Sorted and ordered collections (1)- sorted collections, SortedMap,SortedSet
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.
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请
点击举报。