0

I would like to add a human readable string to a query in CriteriaQuery (jpa with Hibernate 4.3.7 Final)

Something that would appear like

select count(id) 
from my_table 
where 
   'My Description Of Query Origin Name' is not null 
   and .....

To allow me to trace the origin or certain slow queries within my application.

Cheers

Simon B
  • 1,784
  • 3
  • 21
  • 26

1 Answers1

0

I found a way to do this, which was by implementing a Predicate.

Its a bit of a hack but it works.

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;
   }
}

Hope this helps somebody in the future, if there is some other better way I'm very interested to know what it might be!

Simon B
  • 1,784
  • 3
  • 21
  • 26