本文介绍了使用Mybatis在两个表中插入数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Mybatis的新手,在遇到一些问题时陷入困境

I am very new to Mybatis and stuck in a situation I have some questions

完整的方案是,我需要读取和excel文件,并将excel数据插入数据库中具有主键和外键关系的两个不同表中.我能够读取excel数据并能够将其插入主表中,但实际上并没有获得如何在第二张表中插入数据的问题,问题是我有两个不同的pojo类,每个表的数据都不同,并且每个映射器都有两个.

The complete scenario is I need to read and excel file and insert the excel data in database in two different tables having primary and foreign key relationship .I am able to read the excel data and able to insert in primary table but not getting how to insert data in second table actually the problem is I have two different pojo classes having separate data for for each table two different mappers.

我通过在父类的pojo中定义子表的pojo来实现关联有什么办法可以在两个不同的表中插入数据.可以在单个标记中运行2个插入查询

I am achiving association by defining the pojo of child table inside the pojo of parent classIs there any way to insert data in two different table.Is is possible to run 2 insert queries in single tag

任何帮助都是有意义的

推荐答案

有很多方法可以做到这一点.

There are lot of ways to do that.

这里演示了最简单的方法之一-使用单独的插入.确切的解决方案可能微不足道地变化,这主要取决于主键是从excel中获取还是在插入数据库期间生成的.在这里,我假设密钥是在插入过程中生成的(因为这是一个稍微复杂的情况)

Here is demonstration of one of the most straightforward ways to do that - using separate inserts. The exact solution may vary insignificantly depending mainly on whether primary keys are taken from excel or are generated during insertion into database. Here I suppose that keys are generated during insertion (as this is a slightly more complicated case)

假设您有以下POJO:

Let's assume you have these POJOs:

class Parent {
   private Integer id;
   private Child child;
   // other fields, getters, setters etc
}

class Child {
   private Integer id;
   private Parent parent;
   // other fields, getters, setters etc
}

然后,您在mapper中定义两个方法:

Then you define two methods in mapper:

public interface MyMapper {

    @Insert("Insert into parent (id, field1, ...)
         values (#{id}, #{field1}, ...)")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    void createParent(Parent parent);

    @Insert("Insert into child(id, parent_id, field1, ...)
      values (#{id}, #{parent.id}, #{field1}, ...)")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    void createChild(Child child);
}

并使用它们

MyMapper myMapper = createMapper();

Parent parent = getParent();

myMapper.createParent(parent);
myMapper.createChild(parent.getChild());

可以有一个集合来代替一个孩子.在这种情况下,将为每个孩子在循环中执行 createChild .

Instead of single child there can be a collection. In that case createChild is executed in the loop for every child.

在某些数据库中(,<insert id="createParentWithChild"> insert into parent(id, field1, ...) values (#{id}, #{field1}, ...); insert into child(id, parent_id, field1, ...) values (#{child.id}, #{id}, #{child.field1},...) </insert>

和映射器界面中的方法定义:

and method definition in mapper interface:

void createParentWIthChild(Parent parent);

这篇关于使用Mybatis在两个表中插入数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!