When calling method jakarta.persistence.criteria.Expression.as , in all cases, the code is adding "cast" to predicate even if the expression type is the same as the resulting type This affect negatively the query performance as the resulting query plan is not using indexes in the correct way As an example, using SQLServer2005Dialect, a simple string “equals” predicate on field named "empresa" with sql type char(4) results in:
as this field is part of the primary key the resulting query plan performs a scan over the associated clustered index instead of a seek. The code is located in the class org.hibernate.query.sqm.tree.expression.AbstractSqmExpression :
and then org.hibernate.query.sqm.internal.SqmCriteriaNodeBuilder :
Equivalent code in HB 5.0.12 (org.hibernate.jpa.criteria.expression.ExpressionImpl) first evaluates types, and only adds cast when needed:
But also from JPA documentation I undestand that even on different types the cast must not be done (from https://jakarta.ee/specifications/persistence/3.1/apidocs/jakarta.persistence/jakarta/persistence/criteria/expression#as(java.lang.Class) ) "Perform a typecast upon the expression, returning a new expression object. This method does not cause type conversion: the runtime type is not changed. Warning: may result in a runtime failure." Thanks in advance |