学习小记:
准备两个表 t_clazz, t_student,一个班级对应多个学生
创建pojo类...
创建mapper接口:StudentMapper、ClazzMapper
创建mapper映射文件:StudentMapper.xml、ClazzMapper.xml
多对一
多种方式,常见的包括三种:
- 第一种方式:一条SQL语句,级联属性映射。
- 第二种方式:一条SQL语句,association。
- 第三种方式:两条SQL语句,分步查询。(这种方式常用:优点一是可复用。优点二是支持懒加载。)
一:级联属性映射
pojo类Student中添加一个属性:Clazz clazz;标识学生关联的班级对象
studentMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.llw.mybatis.mapper.StudentMapper">
<resultMap id="studentResultMap" type="com.llw.mybatis.pojo.Student">
<id property="sid" column="sid"/>
<result property="sname" column="sname"/>
<result property="clazz.cid" column="cid"/>
<result property="clazz.cname" column="cname"/>
</resultMap>
<select id="selectBySid" resultMap="studentResultMap">
select s.*, c.* from t_student s join t_clazz c on s.cid = c.cid where sid = #{sid}
</select>
</mapper>
测试类
@Test
public void testSelectBysid(){
StudentMapper mapper = SqlSessionUtil.openSession().getMapper(StudentMapper.class);
Student student = mapper.selectBySid(1);
System.out.println(student);
}
结果:
二:association
其他位置都不需要修改,只需要修改StudentMapper.xml中resultMap中的配置:association即可。
<resultMap id="studentResultMap" type="com.llw.mybatis.pojo.Student">
<id property="sid" column="sid"/>
<result property="sname" column="sname"/>
<association property="clazz" javaType="Clazz">
<id property="cid" column="cid"/>
<result property="cname" column="cname"/>
</association>
</resultMap>
结果相同
三:分步查询
其他位置不需要修改,只需要修改以及添加以下三处:
第一处:association中select位置填写sqlId。sqlId=namespace+id。其中column属性作为这条子sql语句的条件。
<resultMap id="studentResultMap" type="Student">
<id property="sid" column="sid"/>
<result property="sname" column="sname"/>
<association property="clazz"
select="com.powernode.mybatis.mapper.ClazzMapper.selectByCid"
column="cid"/>
</resultMap>
<select id="selectBySid" resultMap="studentResultMap">
select s.* from t_student s where sid = #{sid}
</select>
第二处:在ClazzMapper接口中添加方法 selectByCid
package com.llw.mybatis.mapper;
import com.llw.mybatis.pojo.Clazz;
public interface ClazzMapper {
/**
* 根据cid获取Clazz信息
* @param cid
* @return
*/
Clazz selectByCid(Integer cid);
}
第三处:在ClazzMapper.xml文件中进行配置
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.powernode.mybatis.mapper.ClazzMapper">
<select id="selectByCid" resultType="Clazz">
select * from t_clazz where cid = #{cid}
</select>
</mapper>
同时在全局的mybatis配置中加上新的mapper
工作逻辑是先执行StudentMapper的 selectBySid ,即 select s.* from t_student s where sid = #{sid}
这时根据resultMap中的配置 找到ClassMapper的selectByCid 即 select * from t_clazz where cid = #{cid}
执行结果,可以很明显看到先后有两条sql语句执行:
分步优点:
- 第一个优点:代码复用性增强。
- 第二个优点:支持延迟加载。【暂时访问不到的数据可以先不查询。提高程序的执行效率。】
2023-1-30更新到此,后续补全
====================