我目前正在编写一份报告,其中一个字段需要 group_concat。
CriteriaQuery<GameDetailsDto> criteriaQuery = criteriaBuilder
.createQuery(GameDetailsDto.class);
Root<BetDetails> betDetails = criteriaQuery.from(BetDetails.class);
Expression<String> betSelection = betDetails.get("winningOutcome");
criteriaQuery.multiselect(
// other fields to select
criteriaBuilder.function("group_concat", String.class, betSelection),
// other fields to select
);
//predicate, where clause and other filters
TypedQuery<GameDetailsDto> typedQuery = entityManager.createQuery(criteriaQuery);
这在线上抛出一个空指针异常:
TypedQuery<GameDetailsDto> typedQuery = entityManager.createQuery(criteriaQuery);
我是否错误地使用了criteriaBuilder 的函数方法?
文件说:
function(String name, Class<T> type, Expression<?>... args);
最佳答案
我想出了如何使用 Hibernate-jpa-mysql 做到这一点:
1.) 创建了一个扩展 org.hibernate.dialect.function.SQLFunction 的 GroupConcatFunction 类(这是单列 group_concat 现在)
public class GroupConcatFunction implements SQLFunction {
@Override
public boolean hasArguments() {
return true;
}
@Override
public boolean hasParenthesesIfNoArguments() {
return true;
}
@Override
public Type getReturnType(Type firstArgumentType, Mapping mapping)
throws QueryException {
return StandardBasicTypes.STRING;
}
@Override
public String render(Type firstArgumentType, List arguments,
SessionFactoryImplementor factory) throws QueryException {
if (arguments.size() != 1) {
throw new QueryException(new IllegalArgumentException(
"group_concat shoudl have one arg"));
}
return "group_concat(" + arguments.get(0) + ")";
}
}
2.) 我创建了扩展 org.hibernate.dialect.MySQL5Dialect 的 CustomMySql5Dialect 类并注册了在步骤 1 中创建的 group_concat 类
3.) 在应用程序上下文中,我更新了 jpaVendorAdapter 以使用 CustomMySql5Dialect 作为数据库平台
4.) 最后使用它
criteriaBuilder.function("group_concat", String.class,
sampleRoot.get("sampleColumnName"))
关于JPA Criteria API group_concat 用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7005354/