我發現了一個辦法做到這一點,這是通過實施謂語。
它的一些黑客,但它的作品。
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;
}
}
希望這有助於未來的人,如果還有其他更好的方法我很想知道它可能是什麼!