Spring Boot中如何将SQL存储过程结果转为JSON格式?
Spring Boot 处理存储过程返回结果集的正确方式
问题分析
你拿到的{#result-set-1=[{message=Credited Amount: 1.000 , On Card: 000 0040,By: Gab R, code=200}]}是JDBC执行存储过程返回的原始结果集包装结构,直接用正则处理容易出错——message内容里可能包含逗号、等号这类分隔符,会导致匹配逻辑失效,而且这种方式代码维护性极差。
正确处理步骤
1. 定义匹配返回字段的实体类
先创建一个对应返回结果的实体类,用来接收映射后的数据:
public class TransactionResult { private String message; private Integer code; // 生成Getter、Setter方法,也可以用Lombok的@Data注解简化 public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public Integer getCode() { return code; } public void setCode(Integer code) { this.code = code; } }
2. 用Spring JDBC的SimpleJdbcCall映射结果
Spring提供的SimpleJdbcCall可以直接将存储过程的返回结果集映射到实体类,无需手动解析字符串:
import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; import org.springframework.jdbc.core.namedparam.SqlParameterSource; import org.springframework.jdbc.core.simple.SimpleJdbcCall; import java.util.List; import java.util.Map; // 注入JdbcTemplate实例 @Autowired private JdbcTemplate jdbcTemplate; public TransactionResult executeStoredProcedure() { SimpleJdbcCall jdbcCall = new SimpleJdbcCall(jdbcTemplate) .withProcedureName("你的存储过程名称") // 替换为实际存储过程名 // 配置结果集映射规则,#result-set-1要和返回结果里的key完全一致 .returningResultSet("#result-set-1", (rs, rowNum) -> { TransactionResult result = new TransactionResult(); result.setMessage(rs.getString("message")); result.setCode(rs.getInt("code")); return result; }); // 如果存储过程需要入参,在这里添加 SqlParameterSource params = new MapSqlParameterSource(); // params.addValue("参数名", 参数值); Map<String, Object> resultMap = jdbcCall.execute(params); // 从结果集中取出第一个对象 return ((List<TransactionResult>) resultMap.get("#result-set-1")).get(0); }
3. 备选方案:用MyBatis直接映射
如果项目使用MyBatis,可以直接在Mapper接口中定义存储过程调用,结果会自动映射到实体类:
@Mapper public interface TransactionMapper { @Select("CALL 你的存储过程名称(#{参数名})") @Options(statementType = StatementType.CALLABLE) TransactionResult callStoredProcedure(@Param("参数名") String param); }
调用Mapper方法就能直接拿到封装好的TransactionResult对象,代码更简洁。
内容的提问来源于stack exchange,提问作者Gabriel Rogath
相关产品推荐
相关产品推荐

