简体   繁体   English

JAVA | mybatis | 插入多图

[英]JAVA | mybatis | Insert a multimap

I have a use-case wherein i want to insert a multimap ( eg. Multimap ) into database using mybatis. 我有一个用例,其中我想使用mybatis将一个多图(例如Multimap)插入数据库。

i am not able to access key and value in mybatis using the following : (assumed that it would invoke the entrySet and iterate on it internally before inserting) 我无法使用以下命令访问mybatis中的键和值:(假设它会在插入之前调用entrySet并在内部对其进行迭代)

INSERT INTO table1 (integer1, integer2)
VALUES (#{key} , #{value})

Any idea how this can be done ? 任何想法如何做到这一点? I am assuming there should be a straightforward way, as this is a basic use case. 我假设应该有一种简单的方法,因为这是一个基本的用例。

--EDIT-- - 编辑 -

Though i can create a wrapper object, set these values and send them to mybatis, i wanted to know if there is any other way to achieve the end result without creating additional objects, as this is the only place where i need them. 尽管我可以创建包装对象,设置这些值并将其发送给mybatis,但我想知道是否还有其他方法可以在不创建其他对象的情况下达到最终结果,因为这是我唯一需要它们的地方。

Thanks for the help. 谢谢您的帮助。

---EDIT--- Tested after incorporating the suggested solution. ---编辑---在加入建议的解决方案后进行了测试。

Code snippet for details: 有关详细信息的代码段:

DAO layer: DAO层:

Map<String, Object> params = new HashMap<>();
params.put("entries", myMultimap.entries());

Mybatis sql: Mybatis SQL:

INSERT INTO table1
    (integer1, integer2)
VALUES
<foreach item="item" separator="," collection="entries">
   ( #{item.key} , #{item.value} )
</foreach>

--- EDIT --- -编辑-

Guys, with the above solution watch out for max 2000 characters in parameter length. 伙计们,使用上述解决方案时,请注意参数长度最多2000个字符。 If you face the issue, batching/bulk insert will be the way to proceed further. 如果您遇到问题,则批量/批量插入将是进一步进行的方法。

You need 2 tables: KEYS and VALUES where VALUES should have a foreign key column referencing KEYS. 您需要2个表:KEYS和VALUES,其中VALUES应该具有引用KEYS的外键列。 Example: 例:

TABLE KEYS:
| ID | KEY |
| 1  | key1| 

TABLE VALUES:
| ID | KEY_ID | VALUE |
| 1  | 1      | value1|
| 2  | 1      | value2|

Now to persist a multimap you need to first persist the a key in the KEYS table and then the corresponding values in the VALUES table. 现在要保留多图,首先需要将一个键保留在KEYS表中,然后将相应的值保留在VALUES表中。 Let me know if you need an example of that. 让我知道您是否需要一个例子。

EDIT: See comments 编辑:查看评论

You should use the foreach tags in mybatis. 您应该在mybatis中使用foreach标记。 Do a foreach on the keyset or on the entries. 在键集或条目上进行foreach。 Something like this should work: 这样的事情应该起作用:

INSERT INTO table1 (integer1, integer2)
VALUES 
<foreach item="item" seperator="," collection="#{entries}">
       ( #{item.key)},#{item.value})
    </foreach>

Where entries should reference the MultiMap.Entries() 条目应引用MultiMap.Entries()的位置

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

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