在条件api中强制转换表达式的结果

时间:2020-01-18 10:55:03

标签: hibernate jpa substring criteria-api

我有此代码:

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();

s变量为我提供了整数。我想将其用作substring函数的参数。我怎样才能做到这一点?此方法无效。

1 个答案:

答案 0 :(得分:1)

您可以使用以下解决方案:

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();

在此代码段中,我假定您使用的是oracle数据库。 TO_NUMBER函数是特定于oracle的函数,它将第一个参数转换为NUMBER数据类型的值。我想类似的功能应该出现在所有数据库中。

请注意,由于HHH-11938TO_NUMBER函数应在您的休眠方言中声明。就我而言,此函数未在org.hibernate.dialect.Oracle12cDialect中声明。因此,我通过以下方式扩展了该方言:

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) );
   }
}

然后在休眠配置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>