Mybatis插入数据时有外键怎么办?

发布于:2024-02-29 ⋅ 阅读:(80) ⋅ 点赞:(0)

今天在写代码的时候遇到了一个问题:

比方说我的数据库如下:

其中work_position和auth都是外键,关联了另一张表。
但我现在要往mysql里插入一条数据,如下:

insert into t_employee_info(salary, work_time, work_position, auth) VALUES
        (2000,'8:00',1,1)

就会弹出错误:

[2024-02-28 22:30:07] [23000][1452] Cannot add or update a child row: a foreign key constraint fails (`museum`.`t_employee_info`, CONSTRAINT `t_employee_info_t_user_id_fk` FOREIGN KEY (`id`) REFERENCES `t_user` (`id`))
[2024-02-28 22:30:07] [23000][1452] Cannot add or update a child row: a foreign key constraint fails (`museum`.`t_employee_info`, CONSTRAINT `t_employee_info_t_user_id_fk` FOREIGN KEY (`id`) REFERENCES `t_user` (`id`))

搜索了很多解决方法,能在sql查询中解决的办法,比较好的是在运行插入前关闭外键,结束插入时开启外键,如下:

set foreign_key_checks = 0;
insert into t_employee_info(salary, work_time, work_position, auth) VALUES
(2000,'8:00',1,1);
set foreign_key_checks = 1;

但要放在mybatis中运行,就不支持set foreign_key_checks这句话了。

报错提示:

[2024-02-28 22:23:49] [42000][1064] You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'set
[2024-02-28 22:23:49] foreign_key_checks = 1' at line 12
[2024-02-28 22:23:49] [42000][1064] You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'set
[2024-02-28 22:23:49] foreign_key_checks = 1' at line 12 

 最后搜索了很多办法,发现仅仅是一个标点符号:``的问题
将代码修改为:

    <insert id="addEmployeeInfo" keyColumn="id" keyProperty="id" parameterType="com.museum.domain.po.EmployeeInfo" useGeneratedKeys="true">
<!--        set foreign_key_checks = 0;-->
        insert into t_employee_info(salary,work_time,`work_position`,`auth`)
        values (
            #{salary,jdbcType=DOUBLE},
            #{workTime,jdbcType=VARCHAR},
            #{workPosition,jdbcType=INTEGER},
            #{auth,jdbcType=INTEGER}
        )
        set foreign_key_checks = 1;
    </insert>

即在是外键的字段外用``包裹起来即能成功运行。

本文含有隐藏内容,请 开通VIP 后查看

网站公告

今日签到

点亮在社区的每一天
去签到