How can I pass multiple parameters and use them?

44,352

Solution 1

Do not specify parameterType but use @Param annotation on parameters in mapper:

@Mapper
public interface MyMapper {

    void update(@Param("a") A a, @Param("b") B b);

    ...
}

Then reference them in mapping:

<update id="update" > 
   UPDATE SOME WHERE x=#{a.x} AND y=#{b.y}
</update>

Solution 2

Use parameterType="map" and @Param annotation.

Method declared in interface:

void mapCategoryAndPage(@Param("categoryLocalId") Long categoryLocalId, @Param("pageLocalId") Long localId);

It is not required that value of @Param annotation must be equal to name of parameter

<insert id="mapCategoryAndPage" parameterType="map">
    INSERT INTO
        category_page_mapping (
            page_local_id,
            category_local_id)
    VALUES
        (#{pageLocalId},
         #{categoryLocalId});
</insert>
Share:
44,352

Related videos on Youtube

Jin Kwon
Author by

Jin Kwon

I'm a Java learner.

Updated on July 09, 2022

Comments

  • Jin Kwon
    Jin Kwon almost 2 years

    Hi I'm new to myBatis.

    I'm using MyBatis and Spring with mybatis-spring.

    How can I pass two different types of objects as parameters, and how can I use their properties in query?

    <update id="update" parameterType="A, B"> <!-- @@? -->
      UPDATE SOME WHERE x=A.x AND y=B.y <!-- @@? -->
    </update>
    
    • Eric
      Eric almost 10 years
      Put multiple param into a map, as one param.
  • kiwiron
    kiwiron almost 6 years
    Weird! Two downvotes 4 years after answering the question. Would the downvoters like to explain why?
  • brt
    brt over 5 years
    Not the downvoter, but probably because it's only your edit that even mentions multiple objects, which is what the question asked about, and 2. is plain wrong for multiple objects of different types. And you gave no code sample.
  • p91paul
    p91paul about 5 years
    Also option 1 is bad practice (passing a Map instead of the actual parameters is not a good idea) while option 2 is very inconvienent (requires creating a new class every time 2 parameters are required)