mybatis基础04

MyBatis注解开发:指南、缓存与分页插件详解

一、mybatis注解开发

public interface StudentDao2 {

    @Select("select * from student where stu_no = #{stu_no}")
    @Results({
            @Result(property = "stuNo" ,column="stu_no"),
            @Result(property = "stuSex",column = "stu_sex"),
            @Result(property = "birth",column = "stu_birth")
    })
   List<Student> getAll(String stu_no);

    @Insert("insert into student (stu_no,stu_name,stu_sex,stu_birth)values(#{stuNo},#{stuName},#{stuSex},#{birth})")
    int addStudent(Student student);

    @Delete("delete from student where stu_no = #{stu_no}")
    int delOne(String stu_no);

    @Update("update student set stu_name = #{stuName} where stu_no = #{stuNo}")
    int uptStudent(Student student);

}

二、mybatis缓存

MyBatis 中的缓存就是说 MyBatis 在执行一次SQL查询或者SQL更新之后,这条SQL语句并不会消失,而是被MyBatis 缓存起来,当再次执行相同SQL语句的时候,就会直接从缓存中进行提取,而不是再次执行SQL命令。

mybatis的缓存机制有两级:

(1)一级缓存:一级缓存mybatsi已经为我们自动开启,不用我们手动操作,而且我们是关闭不了的!!但是我们可以手动清除缓存。(SqlSession级别.提交事务,缓存清空)

一级缓存失效的情况:

1.不同的SqlSession对应不同的缓存
2.同一个SqlSession但是查询条件不同
3.同一个SqlSession执行两次相同查询之间做了增删改的操作
4.同一个SqlSession执行两次相同查询之间手动清空缓存

@Test
    public void test02() {
        //一级缓存sqlSession级别 同一个sqlsession有效
        SqlSession sqlSession = sqlSessionFactory.openSession();
        UserMapper mapper1 = sqlSession.getMapper(UserMapper.class);
        System.out.println("mapper1 = " + mapper1);
        List<User> users = mapper1.selectList();
        users.forEach(user -> System.out.println("user = " + user));
        /**
         *  一级缓存失效
         *  1.不同sqlSession
         *
         *  相同SQLSession下
         *  2.执行一次增删改
         *  3.清空缓存
         *  4.手动提交事务
         *
         */
        //mapper1.deleteById(随便输入);
        //sqlSession.clearCache();
        //sqlSession.commit();
        UserMapper mapper2 = sqlSession.getMapper(UserMapper.class);
        System.out.println("mapper2 = " + mapper2);
        //当前查询返回的数据结果来自mybatis的缓存    一级缓存    一级缓存默认开启
        users = mapper2.selectList();
        users.forEach(user -> System.out.println("user = " + user));

    }

(2)二级缓存:二级缓存需要我们手动开启。(全局级别 SqlSessionFactory)

<!--开启二级缓存-->

开启二级缓存需要两个步骤,第一步在mybatis的全局配置文件中配置Setting属性,设置名为cacheEnabled的属性值为true即可
<settings>
		<!-- 
			(1):开启二级缓存,这个全局的配置二级缓存
			       默认是开启的,但是还是需要写上,防止版本的更新 
		-->
		<setting name="cacheEnabled" value="true"/>
</settings>	

第二步:在具体需要二级缓存的mapeer映射文件中开启二级缓存,值需要在相应的映射文件中添加一个cache标签即可
2):在相应的映射文件中开启二级缓存
<!-- 开启二级缓存 -->
 <cache></cache>
3)查询数据封装的实体类要实现序列化的接口
4)二级缓存需要在一级缓存关闭或者提交后生效

二级缓存失效的条件:
1.在两次查询之间进行了任意的增删改操作,一级二级缓存同时失效
    @Test
    public void test03(){//验证mybatis的缓存机制  二级缓存 需要配置mybatis-config.xml  和mapper文件

        try {
            InputStream resource = Resources.getResourceAsStream("config/mybatis-config.xml");
            SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(resource);
            SqlSession sqlSession1 = factory.openSession(true);
            SqlSession sqlSession2 = factory.openSession(true);
            SqlSession sqlSession3 = factory.openSession(true);

            StudentDao mapper1 = sqlSession1.getMapper(StudentDao.class);
            StudentDao mapper2 = sqlSession2.getMapper(StudentDao.class);
            StudentDao mapper3 = sqlSession3.getMapper(StudentDao.class);
            List<Student> a1 = mapper1.getAll();
            System.out.println(a1);
            //关闭session将查询结果写入二级缓存
            sqlSession1.close();

            //当对同一张表进行增删改操作后  二级缓存清除
            mapper3.delStudent("2021072901");
           // sqlSession3.close();

            List<Student> a2 = mapper2.getAll();
            System.out.println(a2);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

三、mybatis分页插件

①maven文件中引入依赖

<!-- https://mvnrepository.com/artifact/com.github.pagehelper/pagehelper -->
<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper</artifactId>
    <version>5.2.1</version>
</dependency>

②mybatis配置文件中配置插件

<!--在mybatis配置文件中 配置mybatis插件 -->
	<plugins>
		<plugin interceptor="com.github.pagehelper.PageInterceptor">
			<!-- 配置mysql方言 -->
			<property name="helperDialect" value="mysql" />
			<!-- 设置为true时,如果pageSize=0就会查询出全部的结果 -->
			<property name="pageSizeZero" value="true" />
			<!-- 3.3.0版本可用,分页参数合理化,默认false禁用 -->
			<!-- 启用合理化时,如果pageNum<1会查询第一页,如果pageNum>pages会查询最后一页 -->
			<!-- 禁用合理化时,如果pageNum<1或pageNum>pages会返回空数据 -->
			<property name="reasonable" value="true" />
		</plugin>
	</plugins>

 一般情况参数使用默认值就可以如下:

<!--在mybatis配置文件中 配置mybatis插件 -->
	<plugins>
		<plugin interceptor="com.github.pagehelper.PageInterceptor">
		</plugin>
	</plugins>

        实例

@Test
    public void test04(){
        SqlSession sqlSession = sqlSessionFactory.openSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        //使用分页插件 pageNum 当前是第几页 pageSize 每页显示条数
        PageHelper.startPage(1,5);
        List<User> users = mapper.selectList();
        //users.forEach(user -> System.out.println("user = " + user));

        //详情分页信息
        PageInfo<User> userPageInfo = new PageInfo<>(users);
        long total = userPageInfo.getTotal();
        System.out.println("total = " + total);
        List<User> list = userPageInfo.getList();
        System.out.println("list = " + list);
        System.out.println("userPageInfo = " + userPageInfo);
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值