背景:公司用到MyBatis,学习下resultMap
应用:优化代码,实现复杂业务逻辑
研究方向:1对1查询,1对多查询
1对多查询:
实体类:
public class MisGoods {
private Integer goods_shop;
private Integer goods_id;
private List<MisOrderInfo> info; //如果返回1条数据,MisGoods即可;如果是多条数据,则需List;
//若干set/get 方法
}
*Mapper.xml文件:
<!-- test begin -->
<select id="test" resultMap="test">
select goods_id,goods_shop
from
mis_goods ;
</select>
<resultMap type="MisGoods" id="test">
<result column="goods_id" property="goods_id"/>
<result column="goods_shop" property="goods_shop" />
<!-- info:类中属性名称,good_id是MisGoods类中属性 -->
<!--resultMap中可以放多个collection-->
<collection property="info" column="goods_id" ofType="MisGoods" select="get"/>
</resultMap>
<select id="get" parameterType="int" resultType="MisGoods">
select * from mis_goods ;
select * from mis_goods where goods_id=#{0};
</select>
<!-- test end -->
1对1查询:
public class MisGoods {
private Integer goods_id;
private Integer goods_shop;
private MisOrderInfo order;
}
<!-- test begin -->
<select id="test" resultMap="test">
select
b.goods_id,b.goods_shop,a.info_id,a.info_goods
from mis_order_info a, mis_goods b
where
b.goods_id = a.info_id
and b.goods_id=2;
</select>
<!--order是类属性名 info_id,info_goods都是类MisOrderInfo的属性-->
<resultMap type="MisGoods" id="test">
<id property="goods_id" column="goods_id" />
<result property="goods_shop" column="goods_shop" />
<association property="order" javaType="MisOrderInfo">
<id property="info_id" column="info_id" />
<result property="info_goods" column="info_goods" />
</association>
</resultMap>
<!-- test end -->
鉴别器:
<discriminator javaType="string" column="sex"> 13 <case value="男" resultMap="maleStudentMap"/> 14 <case value="女" resultMap="femaleStudentMap"/> 15 </discriminator>
<discriminator column="during" javaType="_int"> // 形式1:通过resultType设置动态映射信息 <case value="4" resultType="EStudent"> <result column="juniorHighSchool" property="seniorHighSchool"/> </case> // 形式2: 通过resultMap设置动态映射信息 <case value="5" resultMap="dynamicRM"/> <case value="6" resultMap="dynamicRM"/> </discriminator>