如何使用 MyBatis 3.x 插入对象集合? [英] How do I insert collection of objects using MyBatis 3.x?

查看:32
本文介绍了如何使用 MyBatis 3.x 插入对象集合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 MyBatis 的初学者.

I'm a beginner with MyBatis.

我只想知道如何从一个类的实例中插入一组对象.假设我有一个类 User 与一对多关系中的 Note 相关.我只想提一下,我通过 Hibernate 的 hbm2ddl 使用 JPA 2 注释构建了我的模式.我将添加我在下面的示例代码中使用的关键 JPA 注释.

I just want to know how to insert a collection of objects from an instance of a class. Say I have a class User related to a Note in one-to-many relationship. I just like to mention that I built my schema using JPA 2 annotations via Hibernate's hbm2ddl. I'll add the key JPA annotations I used in the sample code below.

这是一个示例:

@Entity
public class User {
    ...
    @OneToMany
    @JoinColumn(name="user")
    public List<Note> getNotes() {...}
    ...
}

现在,每次我在 User 表中插入一些东西时,如果列表不为空,我必须将实例插入到 Note 表中.记下 Note 表中的 @JoinColumn,它应该具有插入用户的 id,我已将其设置为自动生成.

Now, everytime I insert something into User table I have to insert instances into the Note table if the list is not empty. Take note of the @JoinColumn in Note table which should have the id of the inserted User, which I have set to be autogenerated.

有没有人有这样的工作?谢谢.

Has anyone got something like this working? Thanks.

推荐答案

当使用常规的 MyBatis XML 映射配置时,您可以使用如下内容:

When using a regular MyBatis XML mapping config you can use something like this:

Java 类:

class EnclosingType {
  private List<ElementType> elements;
}

class ElementType {
  String a;
  String b;
  (...)
}

映射器 xml:

<mapper
    namespace="my.example.ElementType">
    <insert id="insertElements" parameterType="EnlosingType">
        INSERT INTO ELEMENTTYPE (enclosingTypeId, column_a, column_b)
        VALUES
        <foreach item="element" index="index" collection="elements"
            open="(" separator="),(" close=")">
            #{id}, #{element.a}, #{element.b}
        </foreach>
    </insert>
</mapper>

这篇关于如何使用 MyBatis 3.x 插入对象集合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆