Sorted collections by R4R Team

We knows that Hibernate support the collections of implementing with java.util.SortedMap and java.util.SortedSet. With annotations we need to declare a sort comparator using @Sort. We need to chose between the comparator types unsorted, natural or custom

Example of sorted collection with @Sort:

@OneToMany(cascade=CascadeType.ALL, fetch=FetchType.EAGER)
@JoinColumn(name="CUST_ID")
@Sort(type = SortType.COMPARATOR, comparator = TicketComparator.class)
public SortedSet<Ticket> getTickets() {
    return tickets;
}

we need to use either a SortedSet or a SortedMap interface. If we use own comparator implementation, you'll also have to specify the implementation class using the comparator attribute.We should have to specifiy a comparator in the mapping file that as given below:

<set name="aliases" 
            table="student_aliases" 
            sort="natural">
    <key column="student"/>
    <element column="name" type="string"/>
</set>

<map name="holidays" sort="my.custom.HolidayComparator">
    <key column="year_id"/>
    <map-key column="hol_name" type="string"/>
    <element column="hol_date" type="date"/>
</map>

We should allow the sort attribute which are unsorted, natural and the name of a class implementing with java.util.Comparator. We knows that sorted element collection actually behave like the java.util.TreeSet or java.utill.TreeMap. It we want to do by his self the order the collection element use the order-by attribute of set, bag or map mapping. So then we found the solution which is available under the JDK 1.4 or higher (It is implementing using LinkedHashSet or LinkedHashMap). This action can perform the ordering in the SQL query, not done in memory.

<set name="aliases" table="studetn_aliases" order-by="lower(name) asc">
    <key column="student"/>
    <element column="name" type="string"/>
</set>

<map name="holidays" order-by="hol_date, hol_name">
    <key column="year_id"/>
    <map-key column="hol_name" type="string"/>
    <element column="hol_date type="date"/>
</map>

we have to always remember that the value of the order-by attribute in SQL ordering, not a HQL ordering ! Association may even be sorted by some arbitrary criteria at runtime using collection filter().

sortedUsers = s.createFilter( group.getUsers(), "order by this.name" ).list();
Leave a Comment:
Search
Categories
R4R Team
R4Rin Top Tutorials are Core Java,Hibernate ,Spring,Sturts.The content on R4R.in website is done by expert team not only with the help of books but along with the strong professional knowledge in all context like coding,designing, marketing,etc!