SpringBoot集成Spring JDBC插入数据返回415错误该如何解决?
问题原因
- 415 Unsupported Media Type报错
你的POST请求未携带正确的Content-Type请求头,后端@RequestBody注解默认只能解析application/json类型的请求体,你当前请求的Content-Type为application/octet-stream(二进制流类型),Spring MVC无法将请求体解析为StudentClass对象,直接抛出类型不支持错误。 - DAO层插入逻辑存在参数错误
就算解决了415问题,插入操作仍然会失败:你的插入SQL声明了4个字段,对应4个占位符,但最后一个参数传入的是student.getId(),而非所需的student.getAge()。且你请求体中没有传递id参数,此时id为null,完全不符合字段要求。
解决方法
- 修正请求头参数
调用接口时在请求头中添加Content-Type: application/json:- 如果使用Postman测试,Body选择raw类型,右侧格式选JSON即可自动添加该请求头
- 如果使用curl请求,添加
-H "Content-Type: application/json"参数即可
- 修复DAO层插入方法的参数错误
将StudentDaoClass中insert方法的最后一个参数替换为age字段,修正后代码如下:
@Override public int insert(StudentClass student) { String query="INSERT INTO Student(std_name,std_email,std_dob,std_age)" + "VALUES(?,?,?,?)"; int res=this.jdbctemplate.update(query,student.getName(),student.getEmail(),student.getDob(),student.getAge()); return res; }
- 可选优化
如果需要获取插入后自动生成的自增ID,可以使用GeneratedKeyHolder实现,无需手动处理id字段赋值。
内容的提问来源于stack exchange,提问作者Satyaki Sen
相关产品推荐
相关产品推荐

