MyBatis查询汇总

<select id :和dao层方法名相同

resultType / resultMap:二选一

resultType的值是一个类或者int ,比如com.business.entity.RepayChannel

resultMap是在本xml下定义的一个字段集合,比如Integer

现在有储蓄卡表deposit(id,card_no)、还款渠道表channel(id,name)、中间表deposit_channel(id,deposit_id,channel_id)

deposit和channel的关系是一对多,关系记录在中间表deposit_channel

现在希望实现一个接口selectDeposit:查询出多条储蓄卡,且每条都包含它所属的所有渠道。

1、修改deposit的entity,加入属性(不会影响其他查询deposit记录但不需要渠道记录的接口)

private List<Channel> channels

2、mapper.xml

<sql id="Base_Column_List">
id,card_no
</sql>
<resultMap id="DepositChannelResult" type="com.cardniu.ccrepayment.business.entity.Deposit">
<id column="id" property="id" jdbcType="BIGINT"/>
<result column="card_no" property="cardNo" jdbcType="VARCHAR"/>
<!--collection的column表示关联性,此处相当于deposit.id=channel.id-->
<collection property="channels" javaType="ArrayList" column="id" ofType="com.business.entity.Channel" select="selectChannelForDeposit"/>
</resultMap>
<!--此处parameterType和DepositChannelResult中collection的column的类型一致-->
<!--此关联查询如果传参有多个,parameterType要改为map,这里只有id,所以不改-->
<select id="selectChannelForDeposit" resultType="com.business.entity.Channel" parameterType="int">
select 
R.name
from deposity_channel D, channel R 
where D.deposit_id=#{deposit_id} and D.channel_id=R.id
</select>
<select id="selectDeposit" resultMap="DepositChannelResult" parameterType="map">
select 
<include refid="Base_Column_List" /> 
from deposit
</select>

 

 

Done!

 

posted @ 2017-07-20 18:46  行云有影  阅读(655)  评论(0编辑  收藏  举报