编写简单代码往数据库里用户表添加数据
@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设置为自动递增,就能很简单的解决这个问题