mybatis中Resultmap标签的的使用
实体类与表字段映射配置
<!--
自定义映射规则
id 唯一表示符 用于外部引用
type 指定哪个实体的引用规则
-->
<resultMap id="studentmap" type="student">
<!--
主键映射 使用id标签
propetry java中的类型名称
column 数据库中的字段名
-->
<id property="sid" column="s_id"></id>
<!--
普通字段映射 使用id标签
propetry java中的类型名称
column 数据库中的字段名
-->
<result property="sname" column="s_name"></result>
<result property="sage" column="s_age"></result>
<result property="sphone" column="s_phone"></result>
</resultMap>
<!--List<Student> getAllStudent();-->
<select id="getAllStudent" resultMap="studentmap">
SELECT * FROM student
</select>
多对一的映射关系
级联法:将result中的property属性设置成多的那一方的成员变量.成员 column指向表中的字段
<result property="teacher.tname" column="t_name"></result>
<result property="teacher.tage" column="t_age"></result>
使用ossocation标签
<!-- ossociation设用来设置多对一的
proerty是指的多的那个对象 javaType是指的对应的java类型-->
<association property="teacher" javaType="Teacher">
<result property="tid" column="t_id"></result>
<result property="tname" column="t_name"></result>
<result property="tage" column="t_age"></result>
</association>
采用分步查询的方式
<!-- ossociation设用来设置多对一的
proerty是指的多的那个对象
select sql语句的唯一表示符号 namespace.Sql语句id
column 语句要传入下一个查询中的已经从本次查询中查出来的参数
-->
<association property="teacher"
select="com.raoqi.mapper.TeacherMapper.getTeacherById"
column="t_id"
fetchtype="lazy" lazy懒加载 eager不使用懒加载
>
</association>
延迟加载
在分步查询中,如果需要获取到另一个表中的值,才会加载,如果不获取表中的值就不需要加载另一条查询语句
在核心配置文件中设置
<!--开启延迟加载-->
<setting name="lazyLoadingEnabled" value="true"/>
如果是mybatis3.41之前还要配置aggressiveLazyLoading为true
一对多
<resultMap id="teacher" type="Teacher">
<id property="tid" column="t_id"></id>
<result property="tname" column="t_name"></result>
<result property="tage" column="t_age"></result>
<collection property="students" ofType="student">
<id property="sid" column="s_id"></id>
<result property="sage" column="s_age"></result>
<result property="sname" column="s_name"></result>
<result property="sphone" column="s_phone"></result>
</collection>
</resultMap>
如果要使用分步查询方式的话和多对一一样的方式,只不过将ossocation换成collection就行