MyBatis总结(二十七)--任务37:MyBatis_映射文件_select_resultMap_discriminator鉴别器

本文内容来自尚硅谷

本文主要是说明鉴别器的用法,这个鉴别器用的不是很多。代码可以使用MyBatis总结(二十六)--任务35:MyBatis_映射文件_select_resultMap_关联查询_collection分步查询&延迟加载中的代码。也可以自己编写。这里就直接基于MyBatis总结(二十六)--任务35:MyBatis_映射文件_select_resultMap_关联查询_collection分步查询&延迟加载的代码来说明

xml配置如下

如果得到的gender值为0(是女生),则执行case中value值为0的代码即查询出id值就行了

如果得到的gender值为1(是男生),查询出名称,地址等信息不用查询出id值

	<!-- =======================鉴别器============================ -->
	<!-- <discriminator javaType=""></discriminator>
		鉴别器:mybatis可以使用discriminator判断某列的值,然后根据某列的值改变封装行为
		封装Employee:
			如果查出的是女生:就把部门信息查询出来,否则不查询;
			如果是男生,把last_name这一列的值赋值给email;
	 -->
	 <resultMap type="com.atguigu.mybatis.bean.Employee" id="MyEmpDis">
	 	<id column="id" property="id"/>
	 	<result column="last_name" property="lastName"/>
	 	<result column="email" property="email"/>
	 	<result column="gender" property="gender"/>
	 	<!--
	 		column:指定判定的列名
	 		javaType:列值对应的java类型  -->
	 	<discriminator javaType="string" column="gender">
	 		<!--女生  resultType:指定封装的结果类型;不能缺少。/resultMap-->
	 		<case value="0" resultType="com.atguigu.mybatis.bean.Employee">
	 			<association property="dept"
			 		select="com.atguigu.mybatis.dao.DepartmentMapper.getDeptById"
			 		column="d_id">
		 		</association>
	 		</case>
	 		<!--男生 ;如果是男生,把last_name这一列的值赋值给email; -->
	 		<case value="1" resultType="com.atguigu.mybatis.bean.Employee">
		 		<id column="id" property="id"/>
			 	<result column="last_name" property="lastName"/>
			 	<result column="last_name" property="email"/>
			 	<result column="gender" property="gender"/>
	 		</case>
	 	</discriminator>
	 </resultMap>

猜你喜欢

转载自blog.csdn.net/lsx2017/article/details/82721849
今日推荐