How do I insert collection of objects using MyBatis 3.x?

久未见 提交于 2019-11-29 14:43:40

问题


I'm a beginner with MyBatis.

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.

Here's a sample:

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

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.


回答1:


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

Java classes:

class EnclosingType {
  private List<ElementType> elements;
}

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

Mapper 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>


来源:https://stackoverflow.com/questions/3380933/how-do-i-insert-collection-of-objects-using-mybatis-3-x

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!