我想在 CriteriaQuery 中添加一个人类可读的字符串(带有 Hibernate 4.3.7 Final) 的 jpa)
看起来像这样的东西
select count(id)
from my_table
where
'My Description Of Query Origin Name' is not null
and .....
允许我在应用程序中跟踪源或某些慢查询。
干杯
我找到了一种方法来做到这一点,那就是实现一个谓词。
它有点黑客,但它有效。
import com.precurse.frameworks.mwf.util.StringUtil;
import org.hibernate.jpa.criteria.CriteriaBuilderImpl;
import org.hibernate.jpa.criteria.ParameterRegistry;
import org.hibernate.jpa.criteria.compile.RenderingContext;
import org.hibernate.jpa.criteria.expression.UnaryOperatorExpression;
import org.hibernate.jpa.criteria.predicate.AbstractSimplePredicate;
import javax.persistence.criteria.CriteriaBuilder;
import java.io.Serializable;
public class CommentPredicate
extends AbstractSimplePredicate
implements UnaryOperatorExpression<Boolean>, Serializable {
private AbstractSimplePredicate operandExpression;
public CommentPredicate(
CriteriaBuilder criteriaBuilder,
final String _comment) {
super((CriteriaBuilderImpl) criteriaBuilder);
this.operandExpression = new AbstractSimplePredicate((CriteriaBuilderImpl) criteriaBuilder) {
@Override
public void registerParameters(ParameterRegistry registry) {
// do nothing
}
@Override
public String render(boolean isNegated, RenderingContext renderingContext) {
return "'" + StringUtil.escapeForSql(_comment) + "'";
}
};
}
@Override
public AbstractSimplePredicate getOperand() {
return operandExpression;
}
@Override
public void registerParameters(ParameterRegistry registry) {
// nothing to do
}
@Override
public String render(boolean isNegated, RenderingContext renderingContext) {
final String operator = isNegated ? " is null" : " is not null";
return getOperand().render(renderingContext) + operator;
}
}
希望这对将来的某人有所帮助,如果有其他更好的方法,我很想知道它可能是什么!