[英]How to re-use the same SELECT query with two different resultMaps in MyBatis?
我有一个映射器resultMap
有两个我需要选择内联的集合
<collection property="companies" ofType="Company" column="user_id" select="selectCompanies"/>
<collection property="companyGroups" ofType="CompanyGroup" column="user_id" select="selectCompanyGroups"/>
这两个集合的查询完全相同,但是生成的映射彼此非常不同。 有没有一种方法可以对两个不同的resultMaps
使用相同的选择?
我必须内联运行这些查询,因为如果它是主查询的一部分,则由于左联接而将导致额外的数千条记录。
我不能使用SQL,因为它只允许静态参数解析,而不是动态参数解析。
有没有一种方法可以将相同的select与两个不同的
resultMap
一起使用?
是的,您可以将相同的选择与两个不同的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会正确处理它们 。
您的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
, lastName
等的POJO。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.