Announcement Announcement Module
No announcement yet.
Hibernate: getting a sorted loadAll() result... Page Title Module
Move Remove Collapse
Conversation Detail Module
  • Filter
  • Time
  • Show
Clear All
new posts

  • Hibernate: getting a sorted loadAll() result...

    Since I've been told to use HibernateTemplate.loadAll() in my Dao, is there a way to specify the sort order of the returned list?

    When dealing with mapped collections, it's easy to specify the order-by attribute in the mapping so that the sorting is done on the DB.

    When dealing with with loadAll() however, I get whatever order the DB has them in. Is there a mapping setting to push the sorting onto the DB when using loadAll(), or do I have to resort to find("form Object o order by")?

  • #2
    loadAll uses the criteria to load the entities without doing any ordering. You have to alternatives: 1. you can sort the set afterwards , 2. extend the template or use the callback and add the ordering criteria.


    • #3
      I'm trying to use Hibernate callback using a named query.
      Query query = session.getNamedQuery("find.all.users");

      Could you pls tell me how do I provide the ordering info through the above approach.



      • #4
        See the hibernate reference documentation - you can either modify your named query to include an "order by" or if you will always need an order set, modify the mapping so that the returned collection is sorted at retrieval time.


        • #5
          Thanks for the reply.

          I'm displaying a result list on a page which has multiple column names in the list.

          private List findAllUsersTest(final String queryName, final int startRecord, final int endRecord) {
          return getHibernateTemplate().executeFind(new HibernateCallback() {
          public Object doInHibernate(Session session) throws HibernateException, SQLException {
          Query query = session.getNamedQuery(queryName);
          List list = query.list();
          return list;

          The user can sort the list on the page by clicking the column of his choice.
          I dont want to write 10 named queries (5 for asc and 5 for desc) if I have 5 columns in the list.
          So I'm using a fixed named query.
          Is there a way that I could sort the returned collection by providing the column that I need to sort on?


          • #6
            named queries are static - if you want to be able to select the column and the ordering direction then externalize these from your query so you can set it up when executing the query.
            Basically, write the query as if it's not named and add the asc/desc as well as the column programaticaly and then simply externalize the query but keep the attribute binding inside your code. See Hibernate reference documentation for more info.


            • #7
              loadAll with criteria(order) example

              Originally posted by Costin Leau View Post
              loadAll uses the criteria to load the entities without doing any ordering. You have to alternatives: 1. you can sort the set afterwards , 2. extend the template or use the callback and add the ordering criteria.
              Hi Costin

              Don't you have an example lying around.

              I am trying to sort following:
              return getHibernateTemplate().loadAll(ConversionRuleset.c lass);

              I wan't to sort the ConversionRuleset's by letting Hibernate do the sort using the callback and adding an ordering criteria.

              But how do i do that ?

              Anyone have a sample lying around ?

              Best Regards...
              Last edited by Cemil; Sep 28th, 2006, 10:09 AM.


              • #8

                If u want to sort ur models, Firstly u have to implement "Comaprable" Interface,which is the part of "java.lang" package.And then IF u getting collection from the DAO.then write the one line:

                if u r using JDK 1.5
                This will sort the "urDAORetaunredList" alphabeticaly in case of String.

                Model code
                import java.util.Date;
                import javax.persistence.*;
                @Table(name = "routes")
                public class RoutesModel extends AbstractBaseModel implements Comparable<RoutesModel> {
                	private String pattern;
                	private String comment;
                	public RoutesModel(){
                	public void setPattern(String pattern){
                		this.pattern = pattern;
                	@Column(name = "pattern" )
                	public String getPattern(){
                		return this.pattern;
                	public void setComment(String comment){
                		this.comment = comment;
                	@Column(name = "comment" )
                	public String getComment(){
                		return this.comment;
                	public int compareTo(RoutesModel comparedObject) {
                		// TODO Auto-generated method stub
                		return this.getComment().compareToIgnoreCase(comparedObject.getComment());


                • #9
                  Hi shahzad992

                  Thanks a lot.

                  Appreciate youre help.

                  It's working now.

                  Best Regards

                  Cemil Özdemir


                  • #10
                    Hi shahzad992,
                    I have done something similar before using xdoclet tags for hibernate. when retrieving a collection, it works fine and is ordered properly according to my requirement. But when I try to save a collection then it gives a class cast exception.

                    This is my doclet mapping in Abc,

                    * @hibernate.set table="ABC_DEF" cascade="none" "sort="natural"
                    * batch-size="10"
                    * @hibernate.collection-key column="ABC_ID"
                    * @hibernate.collection-many-to-many class=""
                    * column="DEF_ID"

                    Do you have any explanation regarding this situation?



                    • #11
                      Hi Caulfield14 ,

                      From your DAO that extends HibernateDaoSupport, then you can do this :

                      public List getPeople( )
                      Criteria criteria = getSession( ).createCriteria(Person.class);
                      criteria.addOrder(Order.asc( "lastName" ));

                      return criteria.list();

                      No need to do hibernateTemplate.loadAll(Person.class)