有没有一种方法,我可以使用相同的选择与两个不同的resultMap
s?
是的,你可以使用相同的选择与两个不同的resultMap
是这样的。
<mapper namespace="com.example.PersonRepository">
<!-- The common re-usable SELECT query -->
<sql id="select-part">
SELECT first_name, last_name, ...other attributes...
FROM table
<!-- You may use dynamic parameters here the same way as in a regular query -->
<where>
<if test="searchParams.firstName != null">
first_name = #{searchParams.firstName}
</if>
<if test="searchParams.lastName != null">
and last_name = #{searchParams.lastName}
</if>
</where>
</sql>
<!-- Method List<Type1> getAsType1(SearchParams searchParams) -->
<select id="getAsType1" resultMap="map1">
<include refid="select-part"/>
</select>
<!-- Method List<Type2> getAsType2(SearchParams searchParams) -->
<select id="getAsType2" resultMap="map2">
<include refid="select-part"/>
</select>
<resultMap id="map1" type="Type1">
...
</resultMap>
<resultMap id="map2" type="Type2">
...
</resultMap>
</mapper>
不要担心where
和and
条款,MyBatis会handle them correctly。
你的Java代码可能会是这样:
package com.example;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;
// Other imports
@Repository
public interface PersonRepository {
public List<Type1> getAsType1(@Param("searchParams") SearchParams searchParams);
public List<Type2> getAsType2(@Param("searchParams") SearchParams searchParams);
}
和SearchParams
仅仅是一个firstName
POJO,lastName
等
啊完美。所以它就像普通的查询参数图一样工作。非常感谢您的指导 –