Search code examples
javasqlhashmapibatis

Inserting HashMap Values to a table using ibatis


I found this on http://old.nabble.com/insert-statement-td21157498.html I want to do the same thing .I have two columns in my table .I am able to insert hash map values by mapping the hashmap key to the column name.Now i want put the key values pairs in the table irrespective of key name.

Pasted from the link above.

I would like to write a dynamic insert statement, but both fields and values are dynamic.

I mean

<insert id="someIDhere" parameterClass="java.util.HashMap">

    insert into table_one (

        !!! dynamic list of keys from the HashMap

    ) values (

        !!! values

    );

  </insert>

Solution

  • The Hashmap could be:

        HashMap<String,Integer> hm = new HashMap<String, Integer>();
        hm.put("col1", 1);
        hm.put("col2", 23);
        hm.put("col3", 34);
    

    then call the insert someIDhere with the hm as parameter.

    insert into table_one (
    
        COLUMN1, COLUMN2, COLUMN3
    
    ) values (
    
        #col1#, #col2#, #col3#
    
    );