2121import org .springframework .data .repository .query .QueryMethodEvaluationContextProvider ;
2222import org .springframework .data .repository .query .ResultProcessor ;
2323import org .springframework .data .repository .query .ReturnedType ;
24+ import org .springframework .data .util .Lazy ;
2425import org .springframework .expression .spel .standard .SpelExpressionParser ;
2526import org .springframework .lang .Nullable ;
2627import org .springframework .util .Assert ;
3940abstract class AbstractStringBasedJpaQuery extends AbstractJpaQuery {
4041
4142 private final DeclaredQuery query ;
42- private final DeclaredQuery countQuery ;
43+ private final Lazy < DeclaredQuery > countQuery ;
4344 private final QueryMethodEvaluationContextProvider evaluationContextProvider ;
4445 private final SpelExpressionParser parser ;
4546 private final QueryParameterSetter .QueryMetadataCache metadataCache = new QueryParameterSetter .QueryMetadataCache ();
@@ -69,9 +70,10 @@ public AbstractStringBasedJpaQuery(JpaQueryMethod method, EntityManager em, Stri
6970 this .query = new ExpressionBasedStringQuery (queryString , method .getEntityInformation (), parser ,
7071 method .isNativeQuery ());
7172
72- DeclaredQuery countQuery = query .deriveCountQuery (countQueryString , method .getCountQueryProjection ());
73- this .countQuery = ExpressionBasedStringQuery .from (countQuery , method .getEntityInformation (), parser ,
74- method .isNativeQuery ());
73+ this .countQuery = Lazy .of (() -> {
74+ DeclaredQuery countQuery = query .deriveCountQuery (countQueryString , method .getCountQueryProjection ());
75+ return ExpressionBasedStringQuery .from (countQuery , method .getEntityInformation (), parser , method .isNativeQuery ());
76+ });
7577
7678 this .parser = parser ;
7779
@@ -117,7 +119,7 @@ protected ParameterBinder createBinder() {
117119 @ Override
118120 protected Query doCreateCountQuery (JpaParametersParameterAccessor accessor ) {
119121
120- String queryString = countQuery .getQueryString ();
122+ String queryString = countQuery .get (). getQueryString ();
121123 EntityManager em = getEntityManager ();
122124
123125 Query query = getQueryMethod ().isNativeQuery () //
@@ -142,7 +144,7 @@ public DeclaredQuery getQuery() {
142144 * @return the countQuery
143145 */
144146 public DeclaredQuery getCountQuery () {
145- return countQuery ;
147+ return countQuery . get () ;
146148 }
147149
148150 /**
0 commit comments