Search code examples
javaxmlspringibatismybatis

Passing Multiple Parameters in SELECT Statement in MAPPER XML


I am using MyBatis & Spring Framework. I have a DB Table STORE and it has some fields. I need to fetch records from the table using 2 fields in the table, say Name & Id.

select * from STORE where Name="Mels" & Id=123

I am using MAPPER Interface for the table. The MAPPER XML contains the Query.

For a single parameter query, I can use the following..

<select id="findAllSTOREByName"  parameterType="java.lang.String" resultMap="com.StoreObject">
select * from "STORE" where "NAME" = #{name}
</select>

Now, how do I pass multiple parameters like the case I mentioned earlier, with 2 different DataTypes?


Solution

  • you have to use an object of a class, which can store your data (name & id), this could be a hashmap or any other data class.


    before calling your select statement, put the parameters into a hashmap or any other data class and in the select use the name of your value (it is stored in the key field of the hashmap or the name of the attribute of the used class)

    small snippet:

        HashMap<String, Object> values = new HashMap<String, Object>();
        values.put("id", 123);
        values.put("name", "Mels");
    

    ...call findAllStoreByName with the hashmap as parameter

    change your select to the following:

        <select id="findAllSTOREByName"  parameterClass="hashmap"     resultMap="com.StoreObject">
            select * from "STORE" where NAME = #name# and id = #id#
        </select>