You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot原生查询使用GROUP_CONCAT报错:Prepared statement needs to be re-prepared

解决Spring Boot中使用GROUP_CONCAT原生查询时的"Prepared statement needs to be re-prepared"错误

遇到的SQL Error: 1615, SQLState: HY000是MySQL的典型错误,通常和预编译语句缓存不足或查询特性导致缓存失效有关,以下是几种可行的解决方式:

一、调整MySQL服务器缓存参数

这个错误常因MySQL的表定义缓存或预编译语句缓存不足引发,修改配置即可缓解:

  • 编辑MySQL的配置文件(my.cnf/my.ini),添加或修改以下参数:
    table_definition_cache = 4096
    prepared_stmt_cache_size = 65536
    
  • 保存后重启MySQL服务;如果无法重启,可通过SQL语句临时生效(重启后会重置):
    SET GLOBAL table_definition_cache = 4096;
    SET GLOBAL prepared_stmt_cache_size = 65536;
    

二、优化查询语句

调整查询的写法,避免触发预编译语句失效:

  • 给GROUP_CONCAT明确指定分隔符,让语句结构更稳定:
    @Query(value = "select order_id, group_concat(code SEPARATOR ',') from pnt_contracts where order_id = 11186 group by order_id", nativeQuery = true)
    List<Object[]> test();
    
  • 如果order_id是动态参数,改用参数绑定的方式(而非硬编码),能减少预编译缓存冲突:
    @Query(value = "select order_id, group_concat(code) from pnt_contracts where order_id = :orderId group by order_id", nativeQuery = true)
    List<Object[]> test(@Param("orderId") Long orderId);
    

三、禁用Hibernate预编译语句缓存

如果上述方法无效,可临时禁用Hibernate的预编译缓存,代价是轻微的性能损耗:

  • 在application.properties中添加配置:
    spring.jpa.properties.hibernate.statement_cache.size=0
    spring.jpa.properties.hibernate.preparedStatement_cache.size=0
    
  • 或者在application.yml中:
    spring:
      jpa:
        properties:
          hibernate:
            statement_cache:
              size: 0
            prepared_statement_cache:
              size: 0
    

内容的提问来源于stack exchange,提问作者quan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 16:52:44