使用QuerydslR2dbcRepository带参数查询MSSQL报MssqlBadGrammarException
问题解决:QuerydslR2dbcRepository执行SQL Server查询报语法错误(Incorrect syntax near '?')
问题背景
直接使用SQLServer2012Templates执行带Param<LocalDateTime>参数的Querydsl查询时一切正常,DEBUG日志显示com.querydsl.sql.AbstractSQLQuery生成含?的查询语句,但实际发送给SQL Server的语句是适配后的正确版本;但通过QuerydslR2dbcRepository执行相同查询时,抛出异常:
o.r2dbc.mssql.ExceptionFactory$MssqlBadGrammarException: [102] [S0001] Incorrect syntax near '?'
使用的依赖:
implementation 'org.springframework.data:spring-data-r2dbc' implementation 'io.r2dbc:r2dbc-mssql' implementation 'com.infobip:infobip-spring-data-r2dbc-querydsl-boot-starter:7.0.0'
解决方案
1. 强制配置SQL Server专用Querydsl SQL模板
问题核心是QuerydslR2dbcRepository默认未使用SQLServer2012Templates,导致生成的SQL占位符或语法不符合SQL Server要求。通过自定义Bean指定适配模板:
import com.querydsl.sql.SQLServer2012Templates; import com.querydsl.sql.SqlTemplates; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class QuerydslSqlConfiguration { @Bean public SqlTemplates sqlTemplates() { return SQLServer2012Templates.builder() // 按需配置,比如是否用引号包裹标识符 .quote() .build(); } }
2. 验证依赖版本兼容性
Infobip的Querydsl R2DBC Starter版本需与spring-data-r2dbc、r2dbc-mssql版本严格匹配:
- 查看Infobip官方版本对应表,确认
7.0.0版本是否适配当前使用的Spring Data R2DBC版本 - 若存在版本冲突,尝试升级/降级Starter版本至兼容版本
3. 确认参数类型映射与日志排查
- 在Querydsl查询中显式指定
LocalDateTime参数类型,避免隐式映射错误:LocalDateTime param = ...; query.where(qEntity.createdAt.eq(Expressions.asDateTime(param))); - 开启R2DBC DEBUG日志(配置
logging.level.io.r2dbc.mssql=DEBUG),查看实际发送给SQL Server的语句和参数绑定情况,确认占位符是否被正确处理
内容的提问来源于stack exchange,提问作者Adam Krawiec
相关产品推荐
相关产品推荐

