具有休眠标准的COALESCE函数 [英] COALESCE function with hibernate criteria
问题描述
我有一个要求,我需要在休眠条件下使用 COALESCE
?有没有办法来实现这一点?我使用的是hibernate 5.0。
I have a requirement where I need to use COALESCE
with hibernate criteria? Is there are way to implement this? I am using hibernate 5.0.
推荐答案
在JPA规范中有一个API:
CriteriaBuilder.Coalesce
There is an API for this in the JPA specification: CriteriaBuilder.Coalesce
用于构建合并表达式的接口。 coalesce表达式是
等效于一个case表达式,如果它的所有参数
赋值为null,并且返回其第一个非空参数
的值,则返回null。
Interface used to build coalesce expressions. A coalesce expression is equivalent to a case expression that returns null if all its arguments evaluate to null, and the value of its first non-null argument otherwise.
从最新的hibernate版本开始,建议使用JPQL标准而不是特定于hibernate的标准。您最终会得到如下结果: p>
As of latest hibernate versions, it is advised to use the JPQL criteria instead of the hibernate specific ones.. you would end up with something like this:
CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<String> query = cb.createQuery(String.class);
Root<User> user= query.from(User.class);
CriteriaBuilder.Coalesce<String> coalesceExp = builder.coalesce();
coalesceExp.value(user.get("name"));
coalesceExp.value(user.get("surname"));
coalesceExp.value(user.get("middlename"));
query.select(coalesceExp);
Query q = em.createQuery(query);
底线是您使用方法
The bottom line is that you use the method
CriteriaBuilder.Coalesce<T> value(T value)
或
or
CriteriaBuilder.Coalesce<T> value(Expression<? extends T> value)
根据您的需要填充您的coalesc表达式
to fill your coalesc expression per your needs
这篇关于具有休眠标准的COALESCE函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!