Field ‘id’ doesn’t have a default value的解决方法
·
问题描述:
今天在写作业的过程中,发现了这样一个问题:
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.ssm.mapper.GoodsMapper.addGoods-Inline
### The error occurred while setting parameters
### SQL: insert into goods(goodsname,price,quantity)values(?,?,?)
### Cause: java.sql.SQLException: Field 'id' doesn't have a default value
at org.apache.ibatis.exceptions.ExceptionFactory.wrapException(ExceptionFactory.java:30)
at org.apache.ibatis.session.defaults.DefaultSqlSession.update(DefaultSqlSession.java:200)
at org.apache.ibatis.session.defaults.DefaultSqlSession.insert(DefaultSqlSession.java:185)
原因分析:
主要就是 Field ‘id’ doesn’t have a default value,id没有默认值;通过上网查找原因,都是让把主键,也就是id设置自增,但是我个人是不喜欢自增的,但是自增的方法确实可以运行成功,达成目的。找其他方法也找不到,那我就只能自己摸索了。
解决方案:
刚开始我去MySQL设置id的默认值;
像这样,设置id的默认值为0;
虽然说这样是可以运行了,但是有问题:
如图,它默认的id=0,这样显然与我们想要的不符,我们想要的肯定是在4后面加上新的,id应为5;
所以我只能在insert语句做修改了,加注释是我之前的写法,没加注释的是修改的写法。
<insert id="addGoods" parameterType="com.ssm.entity.Goods">
<!-- insert into goods(goodsname,price,quantity)values(#{goodsname},#{price},#{quantity})-->
insert into goods(id,goodsname,price,quantity)values(#{id},#{goodsname},#{price},#{quantity})
</insert>
然后在测试类中,添加id
@Test
public void addGoodsTest() throws Exception{
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
Goods goods = new Goods();
goods.setId(5);
goods.setGoodsname("吹风机");
goods.setPrice(2000);
goods.setQuantity(500);
int rows = sqlSession.insert("com.ssm.mapper.GoodsMapper.addGoods",goods);
if(rows > 0) {
System.out.println("成功添加" + rows + "条数据");
}else System.out.println("添加数据失败!");
sqlSession.commit();
sqlSession.close();
}
运行后就是这样:
这里看是成功运行了,去MySQL上看结果:
成功添加在4后面,id号是自己定的数字,这样就可以不用设置自增了。
更多推荐
目录
所有评论(0)