MyBatis学习笔记③

200 阅读6分钟

resultMap

可以设置主键和普通属性映射关系,其结构是这样的:

<!--
resultMap:设置自定义映射
    属性:
        id:表示自定义映射的唯一标识
        type:查询的数据要映射的实体类的类型
    子标签:
        id:设置主键的映射关系
        result:设置普通字段的映射关系
        association:设置多对一的映射关系
        collection:设置一对多的映射关系
    属性:
        property:设置映射关系中实体类中的属性名
        column:设置映射关系中表中的字段名
-->
<resultMap id="userMap" type="User">
    <id property="id" column="id"></id>
    <result property="userName" column="user_name"></result>
    <result property="password" column="password"></result>
    <result property="age" column="age"></result>
    <result property="sex" column="sex"></result>
</resultMap>
<!--List<User> testMohu(@Param("mohu") String mohu);-->
<select id="testMohu" resultMap="userMap">
    <!--select * from t_user where username like '%${mohu}%'-->
    select id,user_name,password,age,sex from t_user where user_name like
    concat('%',#{mohu},'%')
</select>

老师讲得好清楚!这玩意儿只在select中使用哦!一般用它来处理一对多或多对一关系。

多对一

对一对应对象
先把sql语句放在可视化工具中执行一下,保证没有写错
这里的场景查一下员工是哪个部门的?

级联属性

<resultMap id="empDeptMap" type="Emp">
    <id column="eid" property="eid"></id>
    <result column="ename" property="ename"></result>
    <result column="age" property="age"></result>
    <result column="sex" property="sex"></result>
    <result column="did" property="dept.did"></result>
    <result column="dname" property="dept.dname"></result>
</resultMap>

<!--Emp getEmpAndDeptByEid(@Param("eid") int eid);-->
<select id="getEmpAndDeptByEid" resultMap="empDeptMap">
    select emp.*,dept.* from t_emp emp left join t_dept dept on emp.did = dept.did where emp.eid = #{eid}
</select>

association处理

分步查询

其实也是association的方法,但是这个查询被拆分为多个sql语句

/**
 * 通过分步查询查询员工信息
 * @param eid
 * @return
*/
Emp getEmpByStep(@Param("eid") int eid);
<resultMap id="empDeptStepMap" type="Emp">
    <id column="eid" property="eid"></id>
    <result column="ename" property="ename"></result>
    <result column="age" property="age"></result>
    <result column="sex" property="sex"></result>
    <!--
    select:设置分步查询,查询某个属性的值的sql的标识(namespace.sqlId)
    column:将sql以及查询结果中的某个字段设置为分步查询的条件
    -->
    <association property="dept"
        select="com.atguigu.MyBatis.mapper.DeptMapper.getEmpDeptByStep" 
        column="did">
     <!--fetchType="eager">-->
    </association>
</resultMap>
<!--Emp getEmpByStep(@Param("eid") int eid);-->
<select id="getEmpByStep" resultMap="empDeptStepMap">
    select * from t_emp where eid = #{eid}
</select>
  • select:设置分步查询,查询某个属性的值的sql的标识(namespace.sqlId) 根据部门id查询员工,即使用部门表主键did为条件,来查询满足did条件的员工
  • column:将sql以及查询结果中的某个字段设置为分步查询的条件
/**
 * 分步查询的第二步:根据员工所对应的did查询部门信息
 * @param did
 * @return
*/
Dept getEmpDeptByStep(@Param("did") int did);
<!--Dept getEmpDeptByStep(@Param("did") int did);-->
<select id="getEmpDeptByStep" resultType="Dept">
    select * from t_dept where did = #{did}
</select>

select:设置分步查询,查询某个属性的值的sql的标识(namespace.sqlId)
大家是不是觉得很麻烦,一个sql变成了两个sql语句。nonono,首先这俩分别是两个功能,并且还可以复用!并且它实现了懒加载!(第一次听说是在前端的学习中)
比如当我们只想访问emp.getEmpName()哇哦,amazing,它只会执行第一个sql哦!
但是必须设置全局配置信息!务必不要忘记!

  • lazyLoadingEnabled:延迟加载的全局开关。当开启时,所有关联对象都会延迟加载
  • aggressiveLazyLoading:当开启时,任何方法的调用都会加载该对象的所有属性。 否则,每个属性会按需加载 此时就可以实现按需加载,获取的数据是什么,就只会执行相应的sql。此时可通过associationcollection(下一节讲的一对多在resultMap中使用的标签)中的fetchType属性设置当前的分步查询是否使用延迟加载,fetchType="lazy(延迟加载)|eager(立即加载)"
    当然全局未开启延迟加载时,这两个选项都是立即加载!remember!

一对多

对多对应集合
场景就是查一下部门里有哪些员工?

collection标签

collection专门处理集合,一个属性是property,另一个是javaType,但此时javaType已经被collection标签设置为集合类型了,现在只需要知道集合里存储的数据类型。(类似于泛型)此时是需要声明集合内存放的对象这个标签是ofType

/**
 * 根据部门id查新部门以及部门中的员工信息
 * @param did
 * @return
*/
Dept getDeptEmpByDid(@Param("did") int did);
<resultMap id="deptEmpMap" type="Dept">
    <id property="did" column="did"></id>
    <result property="dname" column="dname"></result>
    <!--
        ofType:设置collection标签所处理的集合属性中存储数据的类型
    -->
    <collection property="emps" ofType="Emp">
        <id property="eid" column="eid"></id>
        <result property="ename" column="ename"></result>
        <result property="age" column="age"></result>
        <result property="sex" column="sex"></result>
    </collection>
    </resultMap>
    <!--Dept getDeptEmpByDid(@Param("did") int did);-->
<select id="getDeptEmpByDid" resultMap="deptEmpMap">
    select dept.*,emp.* from t_dept dept left join t_emp emp on dept.did = emp.did where dept.did = #{did}
</select>

分步查询

/**
 * 分步查询部门和部门中的员工
 * @param did
 * @return
*/
Dept getDeptByStep(@Param("did") int did);
<resultMap id="deptEmpStep" type="Dept">
    <id property="did" column="did"></id>
    <result property="dname" column="dname"></result>
    <collection property="emps" fetchType="eager"
        select="com.atguigu.MyBatis.mapper.EmpMapper.getEmpListByDid" column="did">
    </collection>
</resultMap>
<!--Dept getDeptByStep(@Param("did") int did);-->
<select id="getDeptByStep" resultMap="deptEmpStep">
    select * from t_dept where did = #{did}
</select>

一般只在第一步中设置resultMap,第二步直接用resultType,当然第二步假如也有需要分步查询的话那也resultMap。如五表联查,用用户信息查询角色,角色对应的权限,是两个多对多的关系,所以是两个分步查询实现的。

/**
 * 根据部门id查询员工信息
 * @param did
 * @return
*/
List<Emp> getEmpListByDid(@Param("did") int did);
<!--List<Emp> getEmpListByDid(@Param("did") int did);-->
<select id="getEmpListByDid" resultType="Emp">
    select * from t_emp where did = #{did}
</select>

动态SQL

Mybatis框架的动态SQL技术是一种根据特定条件动态拼装SQL语句的功能,它存在的意义是为了解决 拼接SQL语句字符串时的痛点问题。
如多条件查询,比如你在知网查文献,各种限定的搜索使结果更精确,因此sql语句需要拼接。
本质就是一系列的标签。

if

js编写前端页面时,需要给文本框设置为空字符串来清空文本框,此时获取值就为‘’null,这可以用if判断解决。
回顾一下,xml映射文件的namespace要与接口的全类名一致!

<!--List<Emp> getEmpListByMoreTJ(Emp emp);-->
<select id="getEmpListByMoreTJ" resultType="Emp">
    select * from t_emp where 1=1
    <if test="ename != '' and ename != null">
        and ename = #{ename}
    </if>
    <if test="age != '' and age != null">
        and age = #{age}
    </if>
    <if test="sex != '' and sex != null">
        and sex = #{sex}
    </if>
</select>

if标签可通过test属性的表达式进行判断,若表达式的结果为true,则标签中的内容会执行;反之标签中的内容不会执行。
where 1=1不影响查询结果,还可以方便拼接后续的查询条件,若后面的查询条件都不成立where关键字也可以保留且无影响。

where

where和if一般结合使用:

  • where标签中的if条件都不满足,则where标签没有任何功能,即不会添加where关键字
  • where标签中的if条件满足,则where标签会自动添加where关键字,并将条件最前方多余的and去掉

这样就不需要where=1了

<select id="getEmpListByMoreTJ2" resultType="Emp">
    select * from t_emp
    <where>
        <if test="ename != '' and ename != null">
            ename = #{ename}
        </if>
        <if test="age != '' and age != null">
            and age = #{age}
        </if>
        <if test="sex != '' and sex != null">
            and sex = #{sex}
        </if>
    </where>
</select>

注意:where标签不能去掉条件最后多余的and\

 <if test="ename != '' and ename != null">
            ename = #{ename} and
 </if>

这样的话就去不掉!

trim

它有四个常用的属性!

  • 常用属性:
  1. prefix|suffix:在trim标签中的内容的前面|后面添加某些内容
  2. prefixOverrides|suffixOverrides:在trim标签中的内容的前面去掉某些内容

so我们可以用trim代替when了,哒! 就会变成下面这个样子!

<select id="getEmpListByMoreTJ" resultType="Emp">
    select * from t_emp
    <trim prefix="where" suffixOverrides="and">
        <if test="ename != '' and ename != null">
            ename = #{ename} and
        </if>
        <if test="age != '' and age != null">
            age = #{age} and
        </if>
        <if test="sex != '' and sex != null">
            sex = #{sex}
        </if>
    </trim>
</select>

当然了,若没有内容那trim标签就没有效果
它可以在内容前后去掉或添加内容,很强大

choose、when、otherwise

别怕别怕,它就是if...else if..else

<!--List<Emp> getEmpListByChoose(Emp emp);-->
<select id="getEmpListByChoose" resultType="Emp">
    select <include refid="empColumns"></include> from t_emp
    <where>
    <choose>
        <when test="ename != '' and ename != null">
            ename = #{ename}
        </when>
        <when test="age != '' and age != null">
            age = #{age}
        </when>
        <when test="sex != '' and sex != null">
            sex = #{sex}
        </when>
        <when test="email != '' and email != null">
            email = #{email}
        </when>
    </choose>
    </where>
</select>

这里的when至少一个,otherwise最多一个

foreach

结果是一个集合,可批量操作,如批量添加(“,”连接)批量删除(“or”连接)。
属性:

  1. collection:设置要循环的数组或集合
  2. item:表示集合或数组中的每一个数据
  3. separator:设置循环体之间的分隔符
  4. open:设置foreach标签中的内容的开始符,以什么开始
  5. close:设置foreach标签中的内容的结束符,以什么结束
<!--int insertMoreEmp(List<Emp> emps);-->
<insert id="insertMoreEmp">
    insert into t_emp values
    <foreach collection="emps" item="emp" separator=",">
        (null,#{emp.ename},#{emp.age},#{emp.sex},#{emp.email},null)
    </foreach>
</insert>
<!--int deleteMoreByArray(int[] eids);-->
<delete id="deleteMoreByArray">
    delete from t_emp where
    <foreach collection="eids" item="eid" >
        eid = #{eid}
    </foreach>
</delete>
<!--int deleteMoreByArray(int[] eids);-->
<delete id="deleteMoreByArray">
    delete from t_emp where eid in
    <foreach collection="eids" item="eid" separator="," open="(" close=")">
        #{eid}
    </foreach>
</delete>

separator="or"前后可不兴加空格,因为已经默认加上了。
map结构:array为键,arg为值,用@Param来规定命名

//这里是集合类了so测试代码里
int deleteMoreByArray(@Param("eids") Integer[] eids);

好像新版本中不需要加了。。。

image.png这里不对要写成 image.png,因为数据是集合中循环的每一个对象的属性值,so就是对象.属性

不能在insert循环中添加openclose标签,因为这是整个循环的前后添加,but insert循环的是每个循环体,也就是value()()()like this,不一样哦!

sql

这其实是sql片段,就是我们每次都要写一下常查询的数据库字段这很麻烦。。so引入了一个sql片段,帮助我们简化。sql设置,include引用,直接cv也挺香,但是老师讲是为了我们都能掌握,白学也要学好!看别人的代码也需要!

<sql id="empColumns">
    eid,ename,age,sex,did
</sql>
select <include refid="empColumns"></include> from t_emp

结语

里面比较常用的是if/when/foreach
(每次听老师读when都像while,听到这,恍如隔世,之前的全忘记了。。。)