2017-07-26 256 views
0

我有一个映射resultMap有两个集合,我需要选择在线如何在MyBatis中对两个不同的resultMaps重复使用相同的SELECT查询?

<collection property="companies" ofType="Company" column="user_id" select="selectCompanies"/> 
<collection property="companyGroups" ofType="CompanyGroup" column="user_id" select="selectCompanyGroups"/> 

查询恰好是两个集合,但所得到的地图一样彼此非常不同。有没有一种方法可以使用两个不同的resultMaps相同的选择?

我必须内联运行这些查询,因为如果它是主查询的一部分,由于左连接会导致多出几千条记录。

我不能使用SQL,因为它只允许静态参数解析而不是动态。

回答

2

有没有一种方法,我可以使用相同的选择与两个不同的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> 

不要担心whereand条款,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

+0

啊完美。所以它就像普通的查询参数图一样工作。非常感谢您的指导 –

相关问题