Home » Java » java – Add regular expression in order by clause in criteria builder-Exceptionshub

java – Add regular expression in order by clause in criteria builder-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

We are working on the spring boot project, in which sorting on column number can be applied in ascending and descending order.

We are using a criteria builder to generate the query. Here is the code to order by query to sort :

List<Order> orderBy = new ArrayList<>();
queryContext.getSorts().forEach(sort -> {
     if (sort.getDirection().equals(SortDirection.asc)) {
         orderBy.add(builder.asc(getReference(root, sort.getColumnName())));
     } else {
         orderBy.add(builder.desc(getReference(root, sort.getColumnName())));
     }
});

This worked fine with string. But this is not working for one column that is of string type but it will contain values of float, numbers with or without decimals.

Below query code works fine for the column of string type that will contain values of float, numbers with or without decimal.

orderByClauses.append("regexp_substr(regexp_replace(attribNum, '^\.', '0.'), '^\D*') ");
orderByClauses.append(s.getDirection().toString());
orderByClauses.append(" nulls first,");
orderByClauses.append("to_number(regexp_substr(regexp_replace(attribNum, '^\.', '0.'), '\d+\.?\d*')) ");

How can I add these expressions in criteria builder?

How to&Answers: