简体   繁体   English

如何将SELECT查询的结果分配给mybatis中的java对象?

[英]How to assign the result of a SELECT query to java object in mybatis?

I am trying to insert a list of authors into Author table in mybatis mapper xml using foreach loop as below, 我正在尝试使用如下所示的foreach循环将作者列表插入mybatis mapper xml中的Author表中,

AuthorVO.java 作者VO.java

class AuthorVO {
private List<Author> authors;
...
} 

Author.java 作者.java

class Author{
private int id;
private String name;
private String level;
....
}

Author.xml Author.xml

<insert id="insertAuthor(authorVO)">
<foreach item="author" index="index" collection="authors">

INSERT into Author (id, name, level)
values
(
(select id from get_next_id where table_name="Author"),
#{author.name},
#{author.level}
)
</insert>

<!-- Need to copy the id value into the author object (author.id) -->

</foreach>

Here I am getting the primary key (id) for Author table from get_next_id table. 在这里,我从get_next_id表中获取Author表的主键(id)。

Now I need to update author.id with the primary key value. 现在,我需要用主键值更新author.id。 Something like: 就像是:

#{author.id} = (select id from get_next_id where table_name="Author")

Please let me know the syntax or correct way of copying the id value from the table into the java pojo object (Author.id)? 请让我知道将ID值从表复制到java pojo对象(Author.id)的语法或正确方法吗?

Try using selectKey without foreach and looping thru collection in your java code instead: 尝试在没有foreach的情况下使用selectKey并在您的Java代码中循环遍历集合:

<insert id="insertAuthor(authorVO)">
    <selectKey keyProperty="author.id" keyColumn="id" resultType="int" order="BEFORE">
        select id from get_next_id where table_name="Author"
    </selectKey>

    INSERT into Author (id, name, level)
    values
    (
         #{author.id},
         #{author.name},
         #{author.level}
    )
</insert>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM