Jin Kwon
Jin Kwon

Reputation: 21978

How can I pass multiple parameters and use them?

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>

Upvotes: 25

Views: 56040

Answers (3)

William
William

Reputation: 81

Another option for you, you can also use a DTO to carry multiple parameters for mapper to use which is actually not bad especially when there are many parameters for 1 sql.
In this way, you don't need to worry about parameter names because they will be mapped as the same as the field name in the DTO.

Example:

@Mapper
public interface DummyItemMapper {
    void addDummyItem(DummyItemDto dummyItemDto);
}
<mapper namespace="xxx.mapper.DummyItemMapper">
   
   <insert id="addDummyItem">
       insert into dummy_item (dummy_item_id, dummy_item_name)
       values (#{dummyItemId}, #{dummyItemName})          
   </insert>
   
</mapper>

Upvotes: 0

Tural
Tural

Reputation: 1128

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>

Upvotes: 8

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>

Upvotes: 61

Related Questions