【Mybatis】错误处理:java.sql.SQLException: Field 'id' doesn't have a default value

939 阅读1分钟

Error记录贴

异常信息

今天写代码时,向数据库插入一条新数据,后台报了Error👇大概长这样

Error updating database. Cause: java.sql.SQLException: Field 'id' doesn't have a default value 
java.sql.SQLException: Field 'id' doesn't have a default value

错误提示挺清晰的,就是写入时id字段没有默认值

错误原因

  1. 数据库中设置了id为主键
  2. 插入的对象的id属性为空

解决方法

  1. 插入字段的xml的sql语句添加上keyProperty和useGeneratedKeys属性
  • keyProperty设置为主键
  • useGeneratedKeys设置为true
<insert id="insertSelective" parameterType="com.zwt.dataobject.UserPasswordDO" keyProperty="id" useGeneratedKeys="true">
  1. 数据库中该字段要设为自增

image.png