Question

I have a use-case wherein i want to insert a multimap ( eg. Multimap ) into database using mybatis.

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)

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.

Thanks for the help.

---EDIT--- Tested after incorporating the suggested solution.

Code snippet for details:

DAO layer:

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

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. If you face the issue, batching/bulk insert will be the way to proceed further.

Was it helpful?

Solution

You need 2 tables: KEYS and VALUES where VALUES should have a foreign key column referencing 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. Let me know if you need an example of that.

EDIT: See comments

You should use the foreach tags in mybatis. Do a foreach on the keyset or on the entries. 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()

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top