问题描述
我是MyBatis的初学者。
I'm a beginner with MyBatis.
我只想知道如何从类的实例插入一个对象集合。说我有一个用户与一个注释相关的一对多关系。我只是想提到我使用JPA 2注释通过Hibernate的hbm2ddl构建我的模式。我将在下面的示例代码中添加我使用的关键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() {...}
...
}
,每次我插入一些东西到用户表我必须插入实例到注意表,如果该列表不为空。注意在注释表中的@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;
(...)
}
Mapper xml:
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>
这篇关于如何使用MyBatis 3.x插入对象集合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!