mybatis 如何同时向主表和从表插入数据
假设 主表(userinfos):用户id:userid(主键);用户名:username;从表(bankcards):卡号:cardid;userid(外键),money(钱)
用的是mysql数据库
我是这样写的
<insert id="saveUsers" parameterType="user">
insert into userinfos (username) values(#{username})
<selectKey keyProperty="userid" resultType="int">
SELECT LAST_INSERT_ID() AS userid
</selectKey>
</insert>
<insert id="saveCards" parameterType="user">
insert into bankcards (userid,money) values(#{userid},#{money})
</insert>
但是一直报错:
exception
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.dao.DataIntegrityViolationException:
### Error updating database. Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails (`mytest`.`bankcards`, CONSTRAINT `FK_user_card` FOREIGN KEY (`userid`) REFERENCES `userinfos` (`userid`))
### The error may involve com.njbdqn.dao.UsersDao.saveCards-Inline
### The error occurred while setting parameters
### Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails (`mytest`.`bankcards`, CONSTRAINT `FK_user_card` FOREIGN KEY (`userid`) REFERENCES `userinfos` (`userid`))
; SQL []; Cannot add or update a child row: a foreign key constraint fails (`mytest`.`bankcards`, CONSTRAINT `FK_user_card` FOREIGN KEY (`userid`) REFERENCES `userinfos` (`userid`)); nested exception is com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails (`mytest`.`bankcards`, CONSTRAINT `FK_user_card` FOREIGN KEY (`userid`) REFERENCES `userinfos` (`userid`))
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:659)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:563)
javax.servlet.http.HttpServlet.service(HttpServlet.java:710)
javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
求帮助