Ordering of containers

Source: Internet
Author: User
Tags comparable sort

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;
   }
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.