From the database point of view, Set, Map, Bag is unordered, and the list is ordered, this side of the so-called unordered or orderly, refers to the container of objects stored in the database, whether in the order of the container object to store.
However, after you get the data from the database, you may want the set, objects in a container, such as map, can be sorted in a certain order, and you can sort the objects in the container from two levels, one after the data is loaded in the JVM, and the other in the database by using the orders by clause directly.
Using the example set in this article to illustrate that the data is sorted in the JVM, you can use the sort attribute in the mapping file to define the ordering of the container, which applies to set and map, for example:
User.hbm.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping
PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<class name="onlyfun.caterpillar.User" table="user">
....
<set name="emails" table="email" sort="natural">
<key column="id"/>
<element type="java.lang.String"
column="address"/>
</set>
</class>
sort= "natural" means that the object's Comparato () method is used to sort, and the object in the container must have an actual java.lang.Comparable interface. For example, a string has an implementation java.lang.Comparable interface, and the result uses a dictionary order to arrange the objects in the container.
You can implement your own sort by simply defining a category to implement the Java.util.Comparator interface, for example:
CustomComparator.java
package onlyfun.caterpillar;
import java.util.Comparator;
public class CustomComparator implements Comparator {
public int compare(Object o1, Object o2) {
if (((String) o1).equals(o2))
return 0;
return ((Comparable) o1).compareTo(o2) * -1;
}
}