diff --git a/hibernate-core/src/main/java/org/hibernate/sql/ast/spi/AbstractSqlAstTranslator.java b/hibernate-core/src/main/java/org/hibernate/sql/ast/spi/AbstractSqlAstTranslator.java index 3b572047fc..0aeb87474e 100644 --- a/hibernate-core/src/main/java/org/hibernate/sql/ast/spi/AbstractSqlAstTranslator.java +++ b/hibernate-core/src/main/java/org/hibernate/sql/ast/spi/AbstractSqlAstTranslator.java @@ -6830,13 +6830,6 @@ else if ( !supportsRowValueConstructorSyntaxInInList() ) { } } - inListPredicate.getTestExpression().accept( this ); - if ( inListPredicate.isNegated() ) { - appendSql( " not" ); - } - appendSql( " in (" ); - String separator = NO_SEPARATOR; - int bindValueCount = listExpressions.size(); int bindValueMaxCount = bindValueCount; @@ -6872,6 +6865,19 @@ else if ( bindValueCount < bindValuePaddingCount ) { } } + final boolean parenthesis = !inListPredicate.isNegated() + && inExprLimit != 0 && listExpressions.size() > inExprLimit; + if ( parenthesis ) { + appendSql( OPEN_PARENTHESIS ); + } + + inListPredicate.getTestExpression().accept( this ); + if ( inListPredicate.isNegated() ) { + appendSql( " not" ); + } + appendSql( " in (" ); + String separator = NO_SEPARATOR; + final Iterator iterator = listExpressions.iterator(); int itemNumber = 0; while ( iterator.hasNext() && ( inExprLimit == 0 || itemNumber < inExprLimit ) ) { @@ -6895,11 +6901,15 @@ else if ( bindValueCount < bindValuePaddingCount ) { if ( inExprLimit > 0 && bindValueCount > inExprLimit ) { do { - append( ") or " ); - inListPredicate.getTestExpression().accept( this ); if ( inListPredicate.isNegated() ) { + append( ") and " ); + inListPredicate.getTestExpression().accept( this ); appendSql( " not" ); } + else { + append( ") or " ); + inListPredicate.getTestExpression().accept( this ); + } appendSql( " in (" ); separator = NO_SEPARATOR; itemNumber = 0; @@ -6915,13 +6925,23 @@ else if ( bindValueCount < bindValuePaddingCount ) { if ( inClauseParameterPaddingEnabled ) { final Expression lastExpression = itemAccessor.apply( listExpressions.get( listExpressions.size() - 1 ) ); - for ( ; itemNumber < bindValueMaxCount; itemNumber++ ) { + final int end; + if ( inExprLimit > 0 ) { + end = Math.min( bindValueMaxCount, inExprLimit ); + } + else { + end = bindValueMaxCount; + } + for ( ; itemNumber < end; itemNumber++ ) { appendSql( separator ); lastExpression.accept( this ); separator = COMA_SEPARATOR; } } appendSql( CLOSE_PARENTHESIS ); + if ( parenthesis ) { + appendSql( CLOSE_PARENTHESIS ); + } } @Override