date: 2019/8/15 21:23:48
MyBatis的强大特性之一。
1.collection 标签
第一种 一对多查询
先配置一个 resultMap
1 2 3 4 5 6 7 8 9 10
| <resultMap id="model2" type="tdept"> <id column="deptid" property="deptid"/> <result column="dname" property="dname"/> <collection property="tEmps" column="deptid" select="com.xiaolan.mapper.TEmpMapper.selectAllByDId"/> </resultMap>
|
看看 两张表的 查询语句 以及返回 类型
1 2 3 4 5 6
| <select id="selectById" resultMap="model2" parameterType="int"> select * from t_dept where deptid = #{deptid}; </select>
|
1 2 3 4 5 6
| <select id="selectAllByDId" resultType="temp" parameterType="int"> select * from t_emp where depid = #{depid} </select>
|
第二种 一对多查询
新配置一个 resultMap
1 2 3 4 5 6 7 8 9 10 11 12 13
| <resultMap id="" type="tdept"> <id column="deptid" property="deptid"/> <result column="dname" property="dname"/> <collection property="tEmps" ofType="temp"> <id column="empid" property="empid"/> <result column="ename" property="ename"/> <result column="egendar" property="egendar"/> </collection> </resultMap>
|
直接分析下 xml
1 2 3 4 5 6 7 8 9 10
| <select id="selectAll" resultMap="model"> select * from t_dept d , t_emp e where d.deptid = 1 and d.deptid = e.depid </select>
|
2.association 标签
第一种 多对一查询
先配置一个 resultMap
1 2 3 4 5 6 7 8 9 10 11
| <resultMap id="model" type="temp"> <id column="empid" property="empid"/> <result column="ename" property="ename"/> <result column="egendar" property="egendar"/> <association property="dept" javaType="tdept"> <id column="deptid" property="deptid"/> <result column="dname" property="dname"/> </association> </resultMap>
|
看看 两张表的连接 查询语句 以及返回 类型
1 2 3 4
| <select id="findByAlls" resultMap="model"> select * from t_dept d, t_emp e where d.deptid = e.depid and e.empid = 1 </select>
|
第二种 多对一查询
先配置一个 resultMap
1 2 3 4 5 6 7 8 9 10
| <resultMap id="model22" type="temp"> <id column="empid" property="empid"/> <result column="ename" property="ename"/> <result column="egendar" property="egendar"/> <association property="dept" column="depid" select="com.xiaolan.mapper.TDeptMapper.selectByIds"> </association> </resultMap>
|
看看 两张表的 查询语句 以及返回 类型
1 2 3 4 5 6 7 8 9 10 11 12 13
| <select id="selectAllById" resultMap="model22" parameterType="list"> select * from t_emp <where> <foreach collection="list" separator="," close=")" open="empid in (" item="ids"> #{ids} </foreach> </where> </select>
|
1 2 3 4 5 6
| <select id="selectByIds" resultType="tdept" parameterType="int"> select * from t_dept where deptid = #{deptid}; </select>
|