基于一对多的查询:
例:
一个部门中有多个员工。
在部门类中存在员工的集合。查询部门的对象时,返回的集合类型进行list的封装
核心代码
对单一个类型为list的属性的封装
- collection :单独的对象用associate。集合用collection。
- property:类中list对象的名字
- ofType:list的泛型
- colum:传入额外sql的字段名
- select:额外方法的映射接口与方法(全限定路径)
<!--对单一个类型为list的属性的封装-->
<resultMap id="department" type="com.uu.bean.Department">
<id column="id" property="id"/>
<result column="name" property="name"/>
<collection property="listi" ofType="com.uu.bean.Ployer" column="name" select="com.uu.mapper.NewsMapper.getPloyerByDepatrment"/>
</resultMap>
开启延迟加载
mybatis配置中:
<configuration>
<settings>
<!--打开延迟加载全局开关-->
<setting name="lazyLoadingEnabled" value="true" />
<!--不要去积极的查询关联对象-->
<setting name="aggressiveLazyLoading" value="false"/>
<!--覆盖延迟加载的触发方法-->
<setting name="lazyLoadTriggerMethods" value=""/>
</settings>
mapper映射文件中
<mapper namespace="com.uu.mapper.NewsMapper">
<cache/>
开启后,不需要对象中的list属性时就不执行额外sql查询。
配合log4j打印出结果。
完整的mapper映射文件
此处将部门的名字作为查询条件查询出来部门的对象
将该部门对象的名字作为条件查询员工表。
返回的员工不同名字的字段进行处理(resultmap)
<?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.uu.mapper.NewsMapper">
<cache/>
<resultMap id="BaseResultMap" type="com.uu.bean.News">
<id column="id" jdbcType="INTEGER" property="id"/>
<result column="vurl" jdbcType="VARCHAR" property="vurl"/>
<result column="intro" jdbcType="VARCHAR" property="intro"/>
<result column="title" jdbcType="VARCHAR" property="title"/>
<result column="updatetime" jdbcType="TIMESTAMP" property="updatetime"/>
<result column="taglabel" jdbcType="VARCHAR" property="taglabel"/>
</resultMap>
<resultMap id="department" type="com.uu.bean.Department">
<id column="id" property="id"/>
<result column="name" property="name"/>
<collection property="listi" ofType="com.uu.bean.Ployer" column="name" select="com.uu.mapper.NewsMapper.getPloyerByDepatrment"/>
</resultMap>
<select id="list" resultType="com.uu.bean.News">
SELECT * FROM news LIMIT #{id},100
</select>
<insert id="savePloy">
INSERT INTO Ployer(name,department) VALUES(#{name},#{department.name})
</insert>
<insert id="saveDeparentment">
INSERT INTO department(id,name,location) VALUES(#{id},#{name},#{location})
</insert>
<select id="department" resultMap="department">
SELECT * FROM department WHERE name = #{name}
</select>
<select id="getPloyerByDepatrment" resultMap="llsjfkl">
SELECT id, name, Department deptName FROM Ployer WHERE department = #{departmentName}
</select>
<resultMap id="llsjfkl" type="com.uu.bean.Ployer">
<id column="id" property="id"/>
<!--<result column="name" property="name"/>-->
<result column="name" property="name"/>
<result column="deptname" property="departmentName"/>
</resultMap>
</mapper>