3

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.

Symon Kt
  • 73
  • 1
  • 2
  • 11

4 Answers4

6

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);
        }
    });
Incepter
  • 2,711
  • 15
  • 33
1

This is how Implemented it

 private List<Users> findUsers(boolean all, int maxResults, int firstResult, SchoolData data) {
    EntityManager em = getEntityManager(data.getExternalId());
    try {
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery cq = cb.createQuery();
        Root<Users> from = cq.from(Users.class);
        cq.orderBy(cb.desc(from.get("dateCreated")));
        cq.select(cq.from(Users.class));
        Query q = em.createQuery(cq);
        if (!all) {
            q.setMaxResults(firstResult);
            q.setFirstResult(maxResults);
        }
        return q.getResultList();
    } finally {
        em.close();
    }
}
Muyinda Rogers
  • 147
  • 3
  • 13
0

Criteria are passed to Hibernate and are translated to the certain language. They appear after where clause in the select so they all the limitations must be set before executing query. Although you don't see it, there is a query generated and executed when calling criteria.list().

Try the following:

@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;
}
xenteros
  • 15,586
  • 12
  • 56
  • 91
0

Firstly, dates should be stored as dates, not strings. If you are working with a legacy system, it may not be possible to change this, but I'd argue that it probably would make your life easier to bite the bullet and refactor.

As a string, the sort function is working because 05 comes before 06.

I'd suggest using annotation or mapping, as outlined in this question, to convert your string to a date in the pojo so that it is the correct type at least somewhere in your application.

public class StringToDateConverter implements AttributeConverter<Date, String> {
  String convertToDatabaseColumn(Date attribute) { /* Conversion code */ }

  Date convertToEntityAttribute(String dbData) { /* Conversion code */ }
}

and

public class MyPojo {
  @javax.persistence.Convert(converter = StringToDateConverter.class)
  public Date getCreateDate() {
  }
}
Nielsvh
  • 1,151
  • 1
  • 18
  • 31