Wednesday, May 9, 2012

How t send multiple parameters to mybatis xml mapper file?

Problem

Using a single parameter is very easy. The example on page 30 of the user guide shows this (see below). But How do we use multiple parameters?
UserMapper.xml:
<select id=”selectUser” parameterType=”int” resultType=”User”>
  select id, username, hashedPassword
  from some_table
  where id = #{id}</sql>
UserMapper.java:
public interface UserMapper{
  User selectUser(int id);
}

Solution

  1. Add the @Param("name") to your Mapper.java
  2. Change the parameterType in Mapper.xml to "map"

1. Add the @Param("name") to your Mapper.java

UserMapper.java:
import org.apache.ibatis.annotations.Param;
public interface UserMapper{
   User selectUser(@Param("username") String usrename, 
                   @Param("hashedPassword") String hashedPassword);
}

2. Change the parameterType in Mapper.xml to "map"

UserMapper.xml:
<select id=”selectUser” parameterType=”map” resultType=”User”>
  select id, username, hashedPassword
  from some_table
  where username = #{username}
  and hashedPassword = #{hashedPassword}</sql>
 
 
see :
http://code.google.com/p/mybatis/wiki/HowToSelectMultipleParams 

7 comments:

  1. wow... Thank you very much... This is very helpful... :)

    ReplyDelete
  2. Hi, thank for sharing it, do you have other way but NOT using annotation ?

    ReplyDelete
  3. Hi Everybody. I just learning myBatis and have a question regardless the case for pass single parameter. If the value Id ( WHERE clause) is introduced by the user using an p:inputText object ( xhtml file), How and where pass that value to the interface UserMapper ( or mapper)? I suppose it is done using the Bean file but I´m really confused. I appreciate any help and thanks in advance......

    ReplyDelete
  4. Muchas gracias, de bastante ayuda

    ReplyDelete