我对 Mybatis 很陌生,遇到了一些问题
完整的场景是我需要读取和 excel 文件并将 excel 数据插入数据库中的两个具有主键和外键关系的不同表中。
我能够读取 excel 数据并能够在主表中插入,但没有得到如何在第二个表中插入数据实际上问题是我有两个不同的 pojo 类,每个表都有两个不同的映射器的单独数据。
我通过在父类的 pojo 中定义子表的 pojo 来实现关联
有没有办法在两个不同的表中插入数据。
是否可以在单个标签中运行 2 个插入查询
任何帮助都将是可观的
最佳答案
有很多方法可以做到这一点。
这是最直接的方法之一的演示 - 使用单独的插入。确切的解决方案可能变化不大,主要取决于主键是从 excel 中获取还是在插入数据库期间生成。在这里,我假设 key 是在插入期间生成的(因为这是一个稍微复杂的情况)
假设您有这些 POJO:
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 中定义两个方法:
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());
可以有一个集合,而不是单个 child 。在那种情况下
createChild
在每个 child 的循环中执行。在某些数据库(posgresql、sql server)中,您可以在一个语句中插入两个表。然而,查询会更复杂。
另一种可能性是在一个映射器方法中使用多个插入语句。我在 postgresql 中使用了与此类似的代码,并在 xml 中进行了映射:
<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>
和映射器接口(interface)中的方法定义:
void createParentWIthChild(Parent parent);
关于excel - 使用Mybatis在两个Table中插入数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23917540/