MyBaits 插入多方数据出错之keyProperty的运用

来源:互联网 发布:工程图纸软件 编辑:程序博客网 时间:2024/05/21 09:57

今天用Mybaits插入多方数据时报错如下:

org.apache.ibatis.exceptions.PersistenceException: 

### Error updating database.  Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails (`mybatis`.`t_order`, CONSTRAINT `t_order_ibfk_1` FOREIGN KEY (`customer_id`) REFERENCES `t_customer` (`id`))


从上述错误描述中可看出是外键冲突,在看控制台的插入语句:

发现:在插入Order时customer_id 竟然是0,后检查映射器配置文件发现未添加 keyProperty="userId" useGeneratedKeys="true"



在后面添加keyProperty="id" useGeneratedKeys="true"就可以插入成功了。


为什么要添加keyProperty="id" useGeneratedKeys="true"


因为,在默认情况下,insert操作返回的是一个int值,并且不是表示主键id,而是表示当前SQL语句影响的行数

在向数据库插入数据时,需要保留插入数据的主键id,以便进行后续的update操作或者将id存入其他表作为外键。

这时我们就需要将insert插入操作时将返回的主键id绑定到对象中。


<insert id="insertCustomer" parameterType="Customer"  keyProperty="id" useGeneratedKeys="true">

上面配置中,“keyProperty”表示返回的主键id要保存到对象的那个属性也就是名为id的属性中,“useGeneratedKeys”表示主键id为自增长模式。


原创粉丝点击