首先这里有两个表分别是seckill(秒杀表),success_killed(秒杀成功明细表)两个表和seckill和successkilled两个实体类
seckill表:
success_killed:
连个表是靠seckill_id这个字段来进行关联的
1.一对一关系的时候:在seckill实体类中添加successkilled属性
private SuccessKilled successKilled;
在xml配置文件中配置如下:
<resultMap id="seckillMap" type="Seckill">
<id column="seckill_id" property="seckillId"></id>
<result property="name" column="name"/>
<result property="number" column="number"/>
<result property="startTime" column="start_time"/>
<result property="endTime" column="end_time"/>
<result property="createTime" column="create_time"/>
<association property="successKilled" javaType="SuccessKilled">
<result property="userPhone" column="user_phone"/>
<result property="state" column="state"/>
<result property="createTime" column="ctime"/>
</association>
</resultMap>
<select id="findundetailById" resultMap="seckillMap">
select se.seckill_id as seckill_id,
se.name,
se.number,
se.start_time,
se.end_time,
se.create_time,
su.seckill_id as sid,
su.user_phone,
su.state,
su.create_time as ctime
from seckill se LEFT JOIN success_killed su
on se.seckill_id = su.seckill_id
<where>
<if test="id !=null">se.seckill_id = #{id}</if>
</where>
</select>
在result中添加<association>标签,其中property 属性为实体类种的属性名字,column 属性为sql中查询出来的列的名字(有别名的时候是别名的名称,并且不能让列名相同)
2.一对多关系的时候,在seckill实体类中添加successkilled属性
private List<SuccessKilled > successKilleds;
在xml配置文件中配置如下:
<resultMap id="seckillMap" type="Seckill">
<id column="seckill_id" property="seckillId"></id>
<result property="name" column="name"/>
<result property="number" column="number"/>
<result property="startTime" column="start_time"/>
<result property="endTime" column="end_time"/>
<result property="createTime" column="create_time"/>
<collection property="successKilleds"
ofType="com.ygf.domain.SuccessKilled">
<!-- 这里的column对应的是下面查询的别名,而不是表字段名 -->
<!-- property对应JavaBean中的属性名 -->
<id property="seckillId" column="sid"></id>
<result property="userPhone" column="user_phone"/>
<result property="state" column="state"/>
<result property="createTime" column="ctime"/>
</collection>
</resultMap>
在result中添加<collection>标签 其中property为实体类中的属性名,ofType为实体类。