七、MyBatis

七、MyBatis

首先一个全局的配置文件,通过此配置文件才能创建 sqlSessionFactory,由 sqlSessionFactory创建 sqlSession,由 sqlSession对数据库进行操作;
(对于查询操作:sqlSessionFactory.openSession()、sqlSession.close();对于增删改等更新操作,在 sqlSession.close()前要先提交即 sqlSession.commit())

public class AppTest{
    SqlSessionFactory sqlSessionFactory=null;
    @Before
    public void init() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream ins = Resources.getResourceAsStream(resource);
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(ins);
    }
    @Test   /*查询商品信息*/
    public void testGetProductList() throws Exception{
        SqlSession sqlSession=sqlSessionFactory.openSession();
        ProductMapper productMapper=sqlSession.getMapper(ProductMapper.class);
        List<Product> list=productMapper.getProductList();
        // sqlSession.commit();
        sqlSession.close();
        for (Product product : list) {
            System.out.println(product);
        }
    }
    @Test   /*根据id删除商品详情信息*/
    public void testDeleteProductDetail() throws Exception{
        SqlSession sqlSession=sqlSessionFactory.openSession();
        ProductMapper productMapper=sqlSession.getMapper(ProductMapper.class);
        productMapper.deleteProductDetail(6);
        sqlSession.commit();
        sqlSession.close();
    }
}

1. MyBatis 延迟加载原理?

简单的说是,生成代理对象,对象方法调用时执行查询语句;?

1. MyBatis 中 #{} 和 ${} 的区别是什么?

在这里插入图片描述
${value}:① 表示 sql语句的拼接; ② 是 properties文件中的变量占位符;
#{ }:表示 sql的参数占位符。
【例1】模糊查询时:
① 如果使用 #{}占位符 则必须人为在传的参数中加 %:
List<User> list=userMapper.selectUserByName("%王");
② 如果使用 ${} 原始符号则不用人为在传的参数中加 %:
List<User> list=userMapper.selectUserByName("王");
③ order by排序,如果将列名通过参数传入sql,根据传的列名进行排序,写为:order by ${columName};如果用 #{ } 无法实现此功能。
【例2】两者区别用法:

//错误 like是具体的了
select * from users where username like #{aaa}  //like 张
//正确 like模糊查询
select * from users where username like '%${value}%'//like %张%

【例3】模糊查询:

<select id="findAdmin" parameterType="int" resultType="admin">
   select * from admin where id=#{id}
</select>
<select id="findAdminList" parameterType="admin" resultType="admin">
    select * from admin where username=#{username} and password=#{password}
</select>

① 如果输入的是基本数据类型即上方 parameterType的类型(可以直接用 value,不过大多用 对象的字段):like '%${value}%'
② 如果输入的是对象数据类型(直接用 value):like '%${value}%'
查询语句:

定义一个 resultMap,使用 association完成一对一映射;
resultMap 实现一对多映射(用collection):

1.1 动态 SQL:where if test和 sql片段

where和 if test:
where 标签相当于 where关键字,可以自动去除第一个 and;
if 相当于判断,test=“判断条件”;
UserMapper.xml (提取 sql片段前)

<mapper namespace="com.mdd.mapper.UserMapper">

    <select id="findUserList" parameterType="userQueryVo" resultMap="userListMap">
        select id u_id,username u_uaername,age u_age from Users 
        <where>
        	<if test="userCustom!=null">
        		<if test="userCustom.username!=null and userCustom.username!='' ">
        			and username like'%${userCustom.username}%'
        		</if>
        		<if test="userCustom.age!=0">
        			and age>#{userCustom.age}
        		</if>
        		<if>
        			//其他if条件
        		</if>
        	</if>
        </where> 
    </select>
   
</mapper>

UserMapper.xml (提取 sql片段后)

<mapper namespace="com.mdd.mapper.UserMapper">

    <!-- where条件抽取(建议对单表抽取,提高公用性)-->
    <sql id="query_user_where">
       <if test="userCustom!=null">
	   <if test="userCustom.username!=null and userCustom.username!='' ">
	   	and username like'%${userCustom.username}%'
	   </if>
	   <if test="userCustom.age!=0">
	   	and age>#{userCustom.age}
	   </if>
        </if>
    </sql>
    
    <select id="findUserList" parameterType="userQueryVo" resultMap="userListMap">
        //select id u_id,username u_uaername,age u_age from Users where username like '%${userCustom.username}%'
        select id u_id,username u_uaername,age u_age from Users 
        <where>
        	<include refid="query_user_where"/>
        	<include refid="其他条件"/>
        </where> 
    </select>
    
</mapper>

sql片段(foreach的使用)
< foreach>标签:collection:集合属性; open:开始循环时要拼接的字符串; close:结束循环时的字符串; item:每次循环的对象; seperator:分隔符。

<!-- select * from Users where age>10 and id in(1,3,5,7) -->
<foreach collection="ids" open="and id in(" close=")" item="id" seperator=",">
   #{id}
</foreach>
<!-- select * from Users where age>10 and (id=1 or id=3 or id=5 or id=7) -->
<foreach collection="ids" open="and(" close=")"  item="id" seperator="or">
   #{id}
</foreach>

1_1. MyBatis为什么没有实现接口的类就可以调用接口中的方法?

MyBatis通过动态代理的方式实现了只通过 mapper接口而无接口的实现类的方式操作数据库;

2. MyBatis 的延迟加载?

在这里插入图片描述

3. MyBatis 的一级缓存和二级缓存?

一级缓存:是一个 sqlSession级别的;
二级缓存:是包含 sqlSession,是 mapper级别的,同一命名空间。(因为二级缓存可将内存中的数据写入磁盘,所以 POJO类要实现 Serializable接口)
在这里插入图片描述

在这里插入图片描述
【1】二级缓存的配置:
① 开启全局缓存(放在最前面);
② Mapper映射文件中添加一行<cache></cache>,表示开启 mapper的二级缓存;
③ 查询结果映射到 POJO,POJO实现 Serializable;
【2】二级缓存的禁用(禁用一个 statement中的二级缓存,则每次发出此 statement的 sql语句都不是从缓存区拿,而是直接查数据库了):
statement设置禁用:useCache="false"(默认为 true);
【3】刷新缓存:
如果 sqlSession操作 commit,对二级缓存进行刷新,对 statement设置flushCache="false"(默认为 true);

eg:
【1】mybatis配置文件(SqlMapConfig.xml):

<configuration>
    <settings>
        <setting name="lazyLoadingEnabled" value="true"/>//延迟加载
        <setting name="aggressiveLazyLoading" value="false"/>
        <setting name="cacheEnabled" value="true"/>//二级缓存的全局缓存开启(要放在最前面)
    </settings>
    <typeAliase> 
        <package name="com.iotek.po"/>
    </typeAliase>
</configuration>

【2】mapper配置文件(UserMapper.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.zhizuobiao.dao.AdminDao">

	<cache></cache>
	//cache标签参数设置:
	//eviction:队列模(先进先出);flushInterval:刷新奸间隔;size:缓存大小;readonly:只读
	//<cache eviction="FIFO" flushInterval="6000" size="512" readonly="true"/>    
    <select id="findAdmin" parameterType="int" resultType="admin">
        select * from admin where id=#{id}
    </select>    
    
    <select id="findAdminList" parameterType="admin" resultType="admin"
    useCache="false"//(禁用缓存)>
        select * from admin where username=#{username} and password=#{password}
    </select>
    
	<update id="updateApply" parameterType="apply"
	flushCache="false"//刷新缓存>
        update apply set
        hire_id=#{hireId},resum_id=#{resumId},meet_time=#{meetTime}
        where id=#{id}
    </update>

</mapper>

【3】POJO类(User.java):

public class User implements Seriali{
	...
}

4. MyBatis 和 Hibernate 的区别?

Mybatis的 sql语句写在配置文件中,Hibernate可以不写 sql;
在这里插入图片描述

5. MyBatis 有哪些执行器?

在这里插入图片描述

6. MyBatis 有哪几种分页方式?

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

7. MyBatis 分页插件的实现原理是什么?

在这里插入图片描述

8. RowBounds 是一次性查询全部结果吗?为什么?

在这里插入图片描述

9. MyBatis 如何编写一个自定义插件?

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值