Vytsalo
Vytsalo

Reputation: 748

Casting expression's result in criteria api

I have this code:

CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();
CriteriaQuery<Integer> criteriaQuery = criteriaBuilder.createQuery(Integer.class);

Root<Teacher> c = criteriaQuery.from(Teacher.class);

Expression s = criteriaBuilder.locate(c.<String>get("fam"), "-").as(Integer.class);

Integer lastIndex = Integer.valueOf(s.toString());

criteriaQuery.select(criteriaBuilder.max(criteriaBuilder.substring(c.<String>get("fam"),  1, lastIndex-1).as(Integer.class)));

Integer aaa = em.createQuery(criteriaQuery).getSingleResult();

The s variable gives me integer number. I would like to use it as a parameter of substring function. How can I do that? This method doesn't work.

Upvotes: 2

Views: 1388

Answers (1)

SternK
SternK

Reputation: 13041

You can use the following solution:

CriteriaBuilder builder = session.getCriteriaBuilder();
CriteriaQuery<Integer> criteria = builder.createQuery(Integer.class);
Root<Teacher> root = criteria.from(Teacher.class);

Expression<Integer> exp = builder.locate(root.get("fam"), "-");
Expression<Integer> one = builder.literal(1);

Expression<String> numberAsString = builder.substring(
   root.get("fam"),
   one,
   builder.diff(exp, one)
);

Expression<Integer> toNumber = builder.function(
  "TO_NUMBER",
  Integer.class,
  numberAsString
);

criteria.select(
   builder.max(toNumber)
);

Integer result = session.createQuery( criteria ).getSingleResult();

In this code snippet I assumed that you use oracle database. The TO_NUMBER function is the oracle specific function that converts the first parameter to a value of NUMBER datatype. I guess that the similar functions should be present in all databases.

Please also note that due to HHH-11938 the TO_NUMBER function should be declared in your hibernate dialect. In my case this function was not declared in org.hibernate.dialect.Oracle12cDialect. So, I extended this dialect in the following way:

import org.hibernate.dialect.Oracle12cDialect;
import org.hibernate.dialect.function.StandardSQLFunction;
import org.hibernate.type.StandardBasicTypes;

public class MyOracleDialect extends Oracle12cDialect
{
   public MyOracleDialect()
   {
      super();
      registerFunction("to_number", new StandardSQLFunction("to_number", StandardBasicTypes.INTEGER) );
   }
}

And then used it in the hibernate config hibernate.cfg.xml

<!DOCTYPE hibernate-configuration SYSTEM "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.dialect">com.sternkn.hibernate.MyOracleDialect</property>
        ...
    </session-factory>
</hibernate-configuration>

Upvotes: 1

Related Questions