MyBatis_day2

一.select查询返回List/Map

1.查询多条数据返回List
如果使用的是自动映射 , resultType指定的是集合中元素的类型。或者说
理解为想让Mybatis将一条数据封装成哪种类型的java对象。就指定成哪种类型
2.查询返回Map

  • a.查询一条数据返回Map,MyBatis会自动使用表的列名作为key,列值作为value返回.
  • b.查询多条数据返回Map,需要使用@MapKey(“key”)指定封装map的时候所使用的key
    Map中的value就是 一条数据封装成的java对象
接口中:
 public Map<String,Object> getEmpsByIdReturnMap(Integer id);
 
配置文件中:
 <!--public Map<String,Object> getEmpsByIdReturnMap(Integer id); resultType返回的类型与封装的类型要一致-->
    <select id="getEmpsByIdReturnMap" resultType="map">
        select * from tb1_employee where id=#{id}
    </select>
    
测试:
public void testGetEmpsByIdNameReturnMap()throws Exception{
        SqlSessionFactory ssf = getSqlSessionFactory();
        SqlSession session = ssf.openSession();
        try{
            EmployeeMapper employeeMapper = session.getMapper(EmployeeMapper.class);
            Map<String,Object> map = employeeMapper.getEmpsByIdReturnMap(1004);
            System.out.println(map);
        }finally {
            session.close();
        }
    }

二.resultMap 自定义映射

1. association 用来映射联合属性

接口:
 //测试级联外键,查询员工的同时查询员工所属部门信息
        public Employee getEmpAndDepart(Integer id);

配置文件:
  <select id="getEmpAndDepart" resultMap="MyEmpDepart">
        SELECT e.id eid,e.last_name,e.gender,e.email,d.id did,d.dept_name
         FROM tb1_employee e,tb1_depart d
         WHERE e.d_id = d.id AND e.id = #{id};
    </select>
    <resultMap id="MyEmpDepart" type="com.atguigu.mybatis.beans.Employee">
        <id column="eid" property="id"/>
        <result column="last_name" property="lastName"/>
        <result column="gender" property="gender"/>
        <result column="email" property="email"/>
        <!--使用级联的方式
        <result column="did" property="depart.id"/>
        <result column="dept_name" property="depart.departmentName"/>-->
        <!--使用关联映射-->
        <association property="depart" javaType="com.atguigu.mybatis.beans.Department">
            <id column="did" property="id"/>
            <result column="dept_name" property="departmentName"/>
        </association>
    </resultMap>

2.association使用分步查询

接口:
 public Employee getEmpAndDepartStep(Integer id);

员工配置文件:
 <select id="getEmpAndDepartStep" resultMap="MyEmpDepartStep">
       select * from tb1_employee where id=#{id}
 </select>
  <resultMap id="MyEmpDepartStep" type="com.atguigu.mybatis.beans.Employee">
      <id column="id" property="id"/>
      <result column="last_name" property="lastName"/>
      <result column="gender" property="gender"/>
      <result column="email" property="email"/>
      <!--使用association进行分步查询-->
      <association property="depart" javaType="com.atguigu.mybatis.beans.Department"
       select="com.atguigu.mybatis.mapper.DepartmentMapper.getDepartById" column="d_id">
      </association>
  </resultMap>

部门配置文件:
<mapper namespace="com.atguigu.mybatis.mapper.DepartmentMapper">
   <!--public Department getDepartById(Integer id);-->
    <select id="getDepartById" resultType="com.atguigu.mybatis.beans.Department">
        select id,dept_name departmentName from tb1_depart where id=#{id}
    </select>

3.association使用分步查询可以使用延迟加载

在这里插入图片描述

4.collection 用来映射集合类型的联合属性

部门配置文件:(查询各部门下的员工信息)
<select id="getDeptAndEmps" resultMap="MyDeptAndEmps">
       SELECT
        d.id did,d.dept_name,e.id eid,e.last_name,e.gender,e.email
        FROM tb1_depart d LEFT JOIN tb1_employee e
        ON d.id = e.d_id
        WHERE d.id=#{id};
</select>
  <resultMap id="MyDeptAndEmps" type="com.atguigu.mybatis.beans.Department">
      <id column="did" property="id"/>
      <result column="dept_name" property="departmentName"/>
      <!--使用collection映射集合类型的关联属性-->
      <collection property="emps" ofType="com.atguigu.mybatis.beans.Employee">
          <id column="eid" property="id"/>
          <result column="last_name" property="lastName"/>
          <result column="gender" property="gender"/>
          <result column="email" property="email"/>
      </collection>
  </resultMap>

collection使用分步查询
在这里插入图片描述
collection分步查询使用延迟加载
在这里插入图片描述

三.动态sql

  • if: 用于条件的判断. test中写的OGNL表达式.
  • where:用于解决拼装sql的时候where 以及 前面多出或者少and的问题.
  • trim: 用于解决拼装sql的时候前面或者后面 缺少或者多出某些字符的问题
  • set: 用于解决修改操作拼装sql的时候,的问题.
  • choose: 类似于带了break的switch case语句. when可以出现多次 otherwise出现一次.
  • foreach: 主要用于对集合的遍历 . 使用foreach完成Mysql的批量操作.

if,where代码:

 <select id="getEmpsDynamicSql" resultType="com.atguigu.mybatis.beans.Employee">
       select * from tb1_employee
       <where>
         <if test="id!=null">
             and id=#{id}
         </if>
         <if test="lastName!=null &amp;&amp; lastName!=&quot; &quot;">
             and last_name=#{lastName}
         </if>
         <if test="email!=null and email.trim()!=''">
             and email=#{email}
         </if>
         <if test="(&quot;m&quot;).equals(gender) or (&quot;f&quot;).equals(gender)">
             and gender=#{gender}
         </if>
       </where>
    </select>

trim代码:
trim:

  • prefix: 前缀 给拼串后的整个字符串加一个前缀.
  • prefixOverrides: 前缀覆盖 给拼串后的整个字符串去掉前面多余的字符
  • suffix: 后缀 给拼串后的整个字符串加一个后缀
  • suffixOverrides: 后缀覆盖 给拼串后的整个字符串去掉后面多余的字符
select * from tbl_employee  
		<trim prefix="where" suffixOverrides="and">
			<!-- test: OGNL表达式 -->
			<if test="id!=null">
				 id = #{id} and
			</if>
			<if test="lastName!=null &amp;&amp; lastName!=&quot;&quot; ">
				 last_name like #{lastName} and
			</if>
			
			<if test="email!=null and email.trim()!=''">
				 email = #{email} and
			</if>
			<if test="(&quot;m&quot;).equals(gender) or (&quot;f&quot;).equals(gender) ">
				 gender = #{gender}
			</if>	
		</trim>	

set代码:

 <select id="getUpdateSet" resultType="com.atguigu.mybatis.beans.Employee">
        update tb1_employee
        <set>
        <if test="lastName!=null">
            last_name=#{lastName},
        </if>
        <if test="email!=null">
            email=#{email},
        </if>
        <if test="gender!=null">
            gender=#{gender}
        </if>
        </set>
        where id=#{id}
    </select>

choose代码:

 <select id="getEmpsByConditionChoose" resultType="com.atguigu.mybatis.beans.Employee">
       select  * from tb1_employee
       <where>
           <choose>
               <when test="id!=null">
                   id=#{id}
               </when>
               <when test="lastName!=null">
                   last_name=#{lastName}
               </when>
               <otherwise>
                   gender='m'
               </otherwise>
           </choose>
       </where>
    </select>

foreach代码:

 <select id="getForeach" resultType="com.atguigu.mybatis.beans.Employee">
        select * from tb1_employee where id in
           <foreach collection="ids" item="curr_id" open="(" close=")" separator=",">
                #{curr_id}
           </foreach>

    </select>

    <!-- public void addEmps(@Param("emps")List<Employee> emps);-->
    <insert id="addEmps">
        insert into tb1_employee (last_name,gender,email) values
        <foreach collection="emps" item="curr_emp" separator=",">
            (#{curr_emp.lastName},#{curr_emp.gender},#{curr_emp.email})
        </foreach>
    </insert>

四.内置参数

  • a._parameter: 代表整个参数.
    如果是单个参数,则代表整个参数
    如果是多个参数,MyBatis会封装map,_parameter代表封装后的map。
  • b._databaseId:
    如果配置了databaseIdProvider,_databaseId代表当前使用的数据库的别名.

五.抽取可重用的sql

 可以使用<sql id=""></sql> 将重复使用率高的sql语句抽取出来。方便多次使用.
在使用的地方可以用<include refid=""> 来引用已经抽取好的sql.

<!-- sql:  抽取可重用的sql语句-->
	
	<sql id="selectSql">
		select * from 
	</sql>
id值与refid一致
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值