Mybatis 使用discriminator鉴别器映射
程序员文章站
2022-04-22 08:00:18
...
碰见的问题场景:需要根据查询出来的字段的值,分别设置两个不同的字段。这是一个类似java的case when的一个判断。
通过查找相关的资料,知道discriminator可以进行设置,相关的代码如下:
<resultMap id="BaseResultMap" type="com.onlyou.ai.autobt.repository.vo.SampleVO">
<id column="id" jdbcType="BIGINT" property="id" />
<result column="task_id" jdbcType="BIGINT" property="taskId" />
<result column="sample_path" jdbcType="VARCHAR" property="samplePath" />
<result column="source_path" jdbcType="VARCHAR" property="sourcePath" />
<result column="source_name" jdbcType="VARCHAR" property="sourceName" />
<result column="final_value_status" jdbcType="VARCHAR" property="finalValueStatus" />
<result column="sample_detail_list_hash" jdbcType="VARCHAR" property="sampleDetailListHash" />
<result column="status" jdbcType="VARCHAR" property="status" />
<result column="template_no" jdbcType="VARCHAR" property="templateNo" />
<result column="sample_hash" jdbcType="VARCHAR" property="sampleHash" />
<result column="from_sample_id" jdbcType="BIGINT" property="fromSampleId" />
<result column="type" jdbcType="VARCHAR" property="type" />
</resultMap>
<resultMap id="sampleDetailListMapSelect"
type="com.onlyou.ai.autobt.repository.vo.SampleVO">
<collection property="sampleDetailList" javaType="ArrayList" column="{sampleId=id}"
ofType="com.onlyou.ai.autobt.repository.vo.SampleDetailVO"
select="com.onlyou.ai.autobt.repository.mapper.ISampleDetailMapper.selectSampleDetailList">
</collection>
</resultMap>
<resultMap id="subImageListMapSelect"
type="com.onlyou.ai.autobt.repository.vo.SampleVO">
<collection property="subImageList" javaType="ArrayList" column="{sampleId=id}"
ofType="com.onlyou.ai.autobt.repository.vo.SubImageVO"
select="com.onlyou.ai.autobt.repository.mapper.ISubImageMapper.selectSubImageList">
</collection>
</resultMap>
<resultMap id="sampleAssociation" type="com.onlyou.ai.autobt.repository.vo.SampleVO" extends="BaseResultMap">
<discriminator javaType="String" column="type">
<case value="0" resultMap="sampleDetailListMapSelect">
</case>
<case value="1" resultMap="subImageListMapSelect">
</case>
</discriminator>
</resultMap>
<sql id="Base_Column_List">
id, task_id, sample_path, source_path, source_name, final_value_status, sample_detail_list_hash,
status, template_no, sample_hash, from_sample_id,type
</sql>
<select id="selectSampleList" parameterType="map" resultMap="sampleAssociation">
select
<include refid="Base_Column_List" />
from t_sample where 1 = 1
<if test="taskId!=null">
AND task_id = #{taskId}
</if>
<if test="sampleStatus!=null and sampleStatus != ''">
AND status = #{sampleStatus}
</if>
</select>
结果集映射,如果type的值为0 则查询sampleDetailList ,如果为1 则设置subImageList。
其中:
select="com.onlyou.ai.autobt.repository.mapper.ISampleDetailMapper.selectSampleDetailList"是另外一个xml的查询语句,
ofType="com.onlyou.ai.autobt.repository.vo.SampleDetailVO" 是返回的list的元素的类型