Question

i'm new to Hibernate and I am trying to get distinct values from a table ignoring case of the values (upper or lower case. in this case lower). The sql query i want to execute is :

select DISTINCT lower(column1) as column1 from Table

but i want to succeed this with Criteria. I am using projections for this. My code so far is:

   Criteria criteria = getSession().createCriteria(className);
   ProjectionList pList = Projections.projectionList();
   ProjectionList pList2 = Projections.projectionList();
   pList2.add(Projections.distinct(pList.add(Projections.property("column1"), "column1")));
   criteria .addOrder(Order.asc("column1"));
   criteria .setProjection(pList2);
   criteria .setResultTransformer(Transformers.aliasToBean(className));
   List<Object> list = criteria .list();

   //Print out results
   System.out.println(list.size()); // returns 5 instead of 2

but the results are not as expected. I am getting distinct entities but not ignoring the case of the values in column1.

Table
------
column1|column2|... 
------ |-------
aaa    | ...
aAa    |....
BBB    |....
bBB    |....
Bbb    |....

Any help will be much appreciated.

Thanks

Was it helpful?

Solution 2

Thanks for your suggestions. I managed to get the desired result using a query as it was much easier as you suggested. I'm posting my answer as it might help someone in the future

try{
    String MYQUERY = "select DISTINCT lower(column1) as col1 from TABLE order by col1 asc";

    List<(Object)> myList = null;
    SQLQuery query = getSession().createSQLQuery(MYQUERY);
    query.setResultTransformer(Transformers.aliasToBean(className));
    query.addScalar("col1", StandardBasicTypes.STRING);
    myList = query.list();
} catch (HibernateException e) {
    System.out.println(e);
}

Thanks again!

OTHER TIPS

You are not ignoring case because you never added a restriction to ignore case.

You can add an ignore case to your order.

Example:

criteria.addOrder(Order.asc("column1").ignoreCase());
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top