解决异常:Cause: java.sql.SQLException: Field 'id' doesn't have a default value

编写简单代码往数据库里用户表添加数据

        @Override

public Integer saveUserHasKey(User user) {

SqlSession session=null;

Integer result=0;

try {

session= factory.openSession(true);// 默认获取的session不会提交事物 设置为true 执行更新提交事物

session.insert("com.shsxt.mapper.UserMapper.saveUserHasKey", user);

result=user.getId();// 获取主键

} catch (Exception e) {

e.printStackTrace();

}finally{

if(null!=session){

session.close();

}

}

return result;

}

 

xml中编写正确的sql语句

         <!--

                   添加记录返回主键

         -->

         <insert id="saveUserHasKey" parameterType="user" useGeneratedKeys="true" keyProperty="id">

             insert into user(user_name,user_pwd) values(#{userName},#{userPwd})

         </insert>

 

执行测试发生如下异常

            org.apache.ibatis.exceptions.PersistenceException:

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

### The error may involve com.shsxt.mapper.UserMapper.saveUserHasKey02-Inline

### The error occurred while setting parameters

### SQL: insert into user(user_name,user_pwd) values(?,?)

### Cause: java.sql.SQLException: Field 'id' doesn't have a default value     

     

看到自己代码没有错误的情况下,百度了一下,好多结果,一种方法是打开my.ini,查找sql-mode="STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"修改为sql-mode="NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"然后重启MYSQL

还有一种方法就是MySQL 5 uses a strict mode which needs to be disabled.In Windows, Goto Start-->Programs-->MySQL->MySQL Instance Config Wizard. Follow through the Reconfigure Instance option-->Detailed Configuration-->Continue Next a few screens. At the bottom under Enable TCP/IP option there is 'Enable Strict Mode'. Deslect this option (no tick). Save changes and MySQL will restart.

 

我试了几个方法,发现这个问题只需要把自己mysql数据库里,在设计表时主键id设置为自动递增,就能很简单的解决这个问题

 

  • 4
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

楪祈樱满集

你的鼓励将是我创作的最大动力

¥2 ¥4 ¥6 ¥10 ¥20
输入1-500的整数
余额支付 (余额:-- )
扫码支付
扫码支付:¥2
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值