我正在使用 JPA 2.0、Hibernate 4.1.0.Final 和 MySQL 5.5.27。我正在尝试将本机 MySQL 查询转换为 CriteriaBuilder 查询。
final Query query = m_entityManager.createNativeQuery(
"SELECT user_name FROM users WHERE user_name like ? ORDER BY convert(REPLACE(user_name, ?, ''), signed) DESC LIMIT 1")
.setParameter(1, userNamePrefix.toLowerCase() + "%")
.setParameter(2, userNamePrefix);
除了我的条款的“ORDER BY”部分之外,我能够弄清楚每个部分。这是没有 ORDER BY 子句的转换查询...
final CriteriaBuilder builder = m_entityManager.getCriteriaBuilder();
final CriteriaQuery<User> criteria = builder.createQuery(User.class);
final Root<User> user = criteria.from(User.class);
criteria.where(builder.like(user.get(User_.userName), username + "%"));
final TypedQuery<User> query = m_entityManager.createQuery(criteria);
任何想法如何将“ORDER BY convert(REPLACE(user_name, ?, ''), signed)” 写为 JPA?
编辑:我正在尝试下面的“函数”建议,但似乎没有办法让函数的“签名”部分不带引号出现。我尝试了以下...
final Expression<String> usernamePrefixExpr = builder.literal(userNamePrefix);
final Expression<String> emptyStrExpr = builder.literal("");
final Expression<String> replaceFn = builder.function("REPLACE", String.class, user.get(User_.userName), usernamePrefixExpr, emptyStrExpr);
final Expression<String> signedExpr = builder.literal("signed");
final Expression<String> convertExpr = builder.function("CONVERT", String.class, replaceFn, signedExpr);
criteria.orderBy(builder.desc(convertExpr));
但是“签名”被替换为“签名”,这是行不通的。