Symon Kt Symon Kt - 20 days ago 6
Java Question

Criteria ORDER BY date not working?

Can you please help me in solving this problem. I am trying to order the results of an criteria query by date, but I'm not getting the results I need.I saved date in String format,how can i order by date using criteria

The code I'm using is:

@Override
public List<Program> getListProgram() {
Session session=sessionFactory.openSession();
Criteria criteria=session.createCriteria(Program.class);
criteria.addOrder(Order.asc("createdDate"));
List<Program> programs=(List<Program>)criteria.list();
return programs;
}


Results are:

01/02/2009
03/01/2009
04/06/2009
05/03/2009
06/12/2008
07/02/2009


Results should be:

06/12/2008
03/01/2009
01/02/2009
07/02/2009


I need to select the date in the format above.

Your help is much appreciated.

Answer

You have to call criteria.addOrder(Order.asc("createdDate")); before executing the list method on criteria.

@Override
public List<Program> getListProgram() {
    Session session=sessionFactory.openSession();
    Criteria criteria=session.createCriteria(Program.class);
    criteria.addOrder(Order.asc("createdDate"));
    List<Program> programs=(List<Program>)criteria.list();
    return programs;
}

EDIT

In your case, if you want to order by String dates, as i mentionned in the comments, this answer is not the proper you can get ( may be turning creationDate into a Date type is the best! for sure).

You can try some code like :

static final String DF = "DD/MM/YYYY";
static final SimpleDateFormat SDF = new SimpleDateFormat(DF);

@Override
public List<Program> getListProgram() {
    Session session=sessionFactory.openSession();
    Criteria criteria=session.createCriteria(Program.class);
    List<Program> =(List<Program>)criteria.list();
    boolean asc = true;
    programs.sort((a, b) -> {
        int comparison = 0;
        try {
            comparison = SDF.parse(a.getCreatedDate()).compareTo(SDF.parse(b.getCreatedDate()));
        } catch (ParseException e) {
            // handle it!!
        }
        return asc ? comparison : (0-comparison);
    });
    return programs;
}

EDIT 2

If you want to avoid using lambdas, try using this instead :

Collections.sort(programs, new Comparator<Main>() {
        @Override
        public int compare(Program a, Program b) {
            int comparison = 0;
        try {
            comparison = SDF.parse(a.getCreatedDate()).compareTo(SDF.parse(b.getCreatedDate()));
        } catch (ParseException e) {
            // handle it!!
        }
        return asc ? comparison : (0-comparison);
        }
    });
Comments