最近发现sql的嵌套查询比较好,就记一下
解释:
通过 collection 对 List 进行映射
property : 想要添加到类的那个属性上
javaType : 这个属性类型
ofType : 查询到属性具体类型
column : 根据那个表字段查询
# SetmealDao中
<sql id="AllParam">id, name, code, helpCode, sex, age, price, remark, attention, img</sql>
<resultMap id="setmeal" type="com.pojo.Setmeal">
<id property="id" column="id"/>
<result property="name" column="name"/>
<result property="code" column="code"/>
<result property="helpCode" column="helpCode"/>
<result property="sex" column="sex"/>
<result property="age" column="age"/>
<result property="price" column="price"/>
<result property="remark" column="remark"/>
<result property="attention" column="attention"/>
<result property="img" column="img"/>
</resultMap>
<resultMap id="findSetMealIsAll" type="com.pojo.Setmeal" extends="setmeal">
<collection property="checkGroups"
javaType="ArrayList"
ofType="com.itheima.pojo.CheckGroup"
column="id"
select="com.dao.CheckGroupDao.findCheckGroupById">
</collection>
</resultMap>
# 查询语句
<select id="findSetMealIsAll" parameterType="integer" resultMap="findSetMealIsAll">
SELECT <include refid="AllParam"/>
FROM t_setmeal where id=#{id}
</select>
第二个Dao
# CheckGroupDao中
<sql id="AllParam">id, code, name, helpCode, sex, remark, attention</sql>
<resultMap id="CheckGroup" type="com.pojo.CheckGroup">
<id property="id" column="id"/>
<result property="name" column="name"/>
<result property="code" column="code"/>
<result property="helpCode" column="helpCode"/>
<result property="sex" column="sex"/>
<result property="remark" column="remark"/>
<result property="attention" column="attention"/>
</resultMap>
<resultMap id="findCheckGroupById" type="com.pojo.CheckGroup" extends="CheckGroup">
<collection property="checkItems"
ofType="com.itheima.pojo.CheckItem"
column="id"
javaType="ArrayList"
select="com.dao.CheckitemDao.findCheckItemById">
</collection>
</resultMap>
<select id="findCheckGroupById" resultMap="findCheckGroupById">
SELECT <include refid="AllParam"/>
FROM `t_checkgroup` tcg INNER JOIN `t_setmeal_checkgroup` tsc ON tcg.`id` = tsc.`checkgroup_id` WHERE tsc.`setmeal_id`=#{id}
</select>
第三个Dao
# CheckitemDao中
<sql id="allParam">id,code,name,sex,age,price,type,attention,remark</sql>
<resultMap id="CheckItems" type="com.pojo.CheckItem">
<id property="id" column="id"/>
<result property="name" column="name"/>
<result property="code" column="code"/>
<result property="age" column="age"/>
<result property="sex" column="sex"/>
<result property="remark" column="remark"/>
<result property="attention" column="attention"/>
<result property="price" column="price"/>
<result property="type" column="type"/>
</resultMap>
<select id="findCheckItemById" resultMap="CheckItems">
SELECT <include refid="allParam"/>
FROM `t_checkitem` tc INNER JOIN `t_checkgroup_checkitem` tcc ON tc.`id` = tcc.`checkitem_id` WHERE tcc.`checkgroup_id`= #{id}
</select>