java - How to order result of hibernate based on a specific order -


i need send query retrieve values has specific group of characters following:

lets interested in 'xx' should search field value starts 'xx' or has ' xx' (space xx). example xxcdef, pd xxrf , cmkjiek xx valid results.

i have following query returns correct results need sort them in way first return xx @ beginning other results. following:

xxabcd xxpler xxrfkf ab xxab cd xxcd zz xxoi polo xx 

code

criteria criteria = session.createcriteria(name.class, "name")                 .add(restrictions.disjunction()                      .add(restrictions.ilike("name.fname", fname + "%"))                      .add(restrictions.ilike("name.fname", "%" + " " + fname + "%"))                     )                 .setprojection(projections.property("name.fname").as("fname"));         list<string> names = (list<string>) criteria.list(); 

with jpql (hql):

select fname name upper(fname) :fnamestart or upper(fname) :fnamemiddle order (case when upper(fname) :fnamestart 1 else 2 end), fname  query.setparameter("fnamestart", "xx%"); query.setparameter("fnamemiddle", "% xx%"); 

with criteria

with criteria it's trickier. firstly, have resort native sql in order clause. secondly, have bind variable.

public class firstnameorder extends order {     public firstnameorder() {         super("", true);     }      @override     public string tosqlstring(criteria criteria, criteriaquery criteriaquery) throws hibernateexception {         return "case when upper(first_name) ? 1 else 2 end";     } } 

the case expression syntax , upper function name should changed in accordance database (and column name if it's different, of course).

it easy add criteria, there no api bind parameter.

i tried trick hibernate passing in unused variable custom sql restriction used variable in order by clause:

criteria criteria = session.createcriteria(name.class, "name")    .add(restrictions.disjunction()       .add(restrictions.ilike("name.fname", fname + "%"))       .add(restrictions.ilike("name.fname", "%" + " " + fname + "%")))    .setprojection(projections.property("name.fname").as("fname"))    .add(restrictions.sqlrestriction("1 = 1", fname + "%", stringtype.instance))    .addorder(new firstnameorder())    .addorder(order.asc("fname")); 

and works fine.

obviously, solution not recommended , suggest using jpql query.


Comments

Popular posts from this blog

toolbar - How to add link to user registration inside toobar in admin joomla 3 custom component -

linux - disk space limitation when creating war file -