SSM框架一:MyBatis学习(二)

7、分页

思考:为什么要分页?

  • 减少数据的处理量
7.1、使用Limit分页
语法:select * from user limit startIndex,pageSize;
select * from user limit 0,2; //从下标1查2条
select * from user limit 3;//从下标0查3条

使用mybatis实现分页,核心SQL

  1. 接口
    //分页
    List<User> getUserByLimit(Map<String,Integer> map);
  1. Mapper.xml
    <!--分页实现查询-->
    <select id="getUserByLimit" parameterType="map" resultType="com.zhang.pojo.User">
        select * from user limit #{startIndex},#{pageSize};
    </select>
  1. 测试
 @Test
    public void testLimit(){
        //第一步:获取SqlSession对象
        SqlSession sqlSession= MybatisUtils.getSqlSession();
        //方式一:执行SQL
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        Map<String, Integer> stringIntegerHashMap = new HashMap<String,Integer>();
        stringIntegerHashMap.put("startIndex",0);
        stringIntegerHashMap.put("pageSize",2);
        List<User> users=mapper.getUserByLimit(stringIntegerHashMap);
        for (User user:users) {
            System.out.println(user);
        }
        //关闭SqlSession
        sqlSession.close();
    }
7.2、RowBounds分页
  1. 接口
    List<User> getUserByRowBounds();
  1. Mapper.xml文件
    <select id="getUserByRowBounds" resultType="com.zhang.pojo.User">
        select * from user;
    </select>
  1. 测试
    @Test
    public void testRowsBounds(){
        //第一步:获取SqlSession对象
        SqlSession sqlSession= MybatisUtils.getSqlSession();
        //方式一:执行SQL
        //RowBounds实现
        RowBounds rowBounds = new RowBounds(1, 2);
        //通过JAVA代码层面实现分页
        List<User> users=sqlSession.selectList("com.zhang.dao.UserMapper.getUserByRowBounds",null,rowBounds);
        for (User user:users) {
            System.out.println(user);
        }
        //关闭SqlSession
        sqlSession.close();
    }
7.3、分页插件

https://pagehelper.github.io/在这里插入图片描述
了解即可,万一以后公司要使用,要知道查什么东西!

8、使用注解开发

8.1面向接口编程(解耦)
8.2、使用注解开发
  1. 注解在接口上实现
public interface UserMapper {
    @Select("select * from user")
    List<User> getUsers();
}
  1. 需要在核心配置文件中绑定接口
    <!--绑定接口-->
    <mappers>
        <mapper class="com.zhang.dao.UserMapper"/>
    </mappers>
  1. 测试
    本质:反射机制实现
    底层:动态代理!
    Mybatis详细执行流程!
8.3、注解CRUD

我们可以在工具类创建的时候实现自动提交事务!

    public static SqlSession getSqlSession(){
        return sqlSessionFactory.openSession(true); //设置为true
    }
  1. 编写接口,增加注解
public interface UserMapper {
    @Select("select * from user")
    List<User> getUsers();
    @Select("select * from user where id =#{id}")
    User getUserByID(@Param("id") int id);
    @Insert("insert into user(id,username,sex) values(#{id},#{username},#{sex})")
    int addUser(User user);
    @Update("update user set username=#{username} where id=#{id}")
    int updateUser(User user);
    @Delete("delete from user where id =#{id}")
    int deleteUser(@Param("id") int id);
}
  1. 绑定接口
    <!--绑定接口-->
    <mappers>
        <mapper class="com.zhang.dao.UserMapper"/>
    </mappers>
  1. 测试类
public class UserMapperTest {
    @Test
    public void test(){
        //第一步:获取SqlSession对象
        SqlSession sqlSession= MybatisUtils.getSqlSession();
        //方式一:执行SQL
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        List<User> users = mapper.getUsers();
        for (User user:users) {
            System.out.println(user);
        }
        //关闭SqlSession
        sqlSession.close();
    }
    @Test
    public void test1(){
        //第一步:获取SqlSession对象
        SqlSession sqlSession= MybatisUtils.getSqlSession();
        //方式一:执行SQL
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User user=mapper.getUserByID(1);
        System.out.println(user);
        //关闭SqlSession
        sqlSession.close();
    }
    @Test
    public void test2(){
        //第一步:获取SqlSession对象
        SqlSession sqlSession= MybatisUtils.getSqlSession();
        //方式一:执行SQL
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User user=new User(10,"dd","dd");
        mapper.addUser(user);
        //关闭SqlSession
        sqlSession.close();
    }
    @Test
    public void test3(){
        //第一步:获取SqlSession对象
        SqlSession sqlSession= MybatisUtils.getSqlSession();
        //方式一:执行SQL
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User user=new User(10,"aa","dd");
        mapper.updateUser(user);
        //关闭SqlSession
        sqlSession.close();
    }
    @Test
    public void test4(){
        //第一步:获取SqlSession对象
        SqlSession sqlSession= MybatisUtils.getSqlSession();
        //方式一:执行SQL
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        mapper.deleteUser(10);
        //关闭SqlSession
        sqlSession.close();
    }
}

关于@Param注解()

  • 基本类型的参数或者String类型,需要加上
  • 引用类型不需要加
  • 如果只有一个基本类型的话,可以忽略,但是建议大家都加上
  • 我们在SQL中引用的就是我们在@Param("")中设定的属性名
    #{}和${}区别,后者无法防止SQL注入

9、Lombok的使用

Project Lombok is a java library that automatically plugs into your editor and build tools, spicing up your java.
Never write another getter or equals method again, with one annotation your class has a fully featured builder, Automate your logging variables, and much more.
  • java library
  • plus
  • build tools
  • with one annotation your class
    使用步骤:
  1. 在IDEA中安装Lombok插件!
  2. 在IDEA中导入Lombok的jar包
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.10</version>
        </dependency>
  1. 在实体类上加注解
@Getter and @Setter
@FieldNameConstants
@ToString
@EqualsAndHashCode
@AllArgsConstructor, @RequiredArgsConstructor and @NoArgsConstructor
@Log, @Log4j, @Log4j2, @Slf4j, @XSlf4j, @CommonsLog, @JBossLog, @Flogger, @CustomLog
@Data
@Builder
@SuperBuilder
@Singular
@Delegate
@Value
@Accessors
@Wither
@With
@SneakyThrows
@val
@var
experimental @var
@UtilityClass
@Data@AllArgsConstructor@NoArgsConstructor
get、set、toString、hashcode、equals(常用)
@Data
@AllArgsConstructor
@NoArgsConstructor

10、多对一

多对一:

  • 多个学生,对应一个老师
  • 对于学生而言,关联…多个学生,关联一个老师【多对一】
  • 对于老师而言,集合,一个老师有很多学生【一对多】

SQL:
新建学生表(id,name ,tid)和老师表(id,name)
测试环境搭建:

  1. 导入lombok
  2. 新建实体类Teacher、Student
  3. 建立Mapper接口
  4. 建立Mapper.xml文件
  5. 在核心配置文件中绑定注册我们的Mapper接口或者文件
  6. 测试查询是否成功

方式一:按照查询嵌套处理

<!--namespace=绑定一个对应的Dao/Mapper接口-->
<mapper namespace="com.zhang.dao.StudentMapper">
    <select id="getStudent" resultMap="ST">
        <!--select s.id,s.name,t.name from teacher t,student s where t.id=s.tid;-->
        select * from student;
    </select>
    <resultMap id="ST" type="com.zhang.pojo.Student">
        <result property="id" column="id"/>
        <result property="name" column="name"/>
        <!--复杂的属性我们需要单独处理  对象:association 集合:collection-->
        <association property="teacher" column="tid" javaType="com.zhang.pojo.Teacher" select="getTeacher"/>
    </resultMap>
    <select id="getTeacher" resultType="com.zhang.pojo.Teacher">
        select * from teacher where id = #{tid};
    </select>
</mapper>

方式二:按照结果嵌套处理

    <!--按照结果嵌套处理-->
    <select id="getStudent2" resultMap="ST2">
        select s.id sid,s.name sname,t.name tname from teacher t,student s where t.id=s.tid;
    </select>
    <resultMap id="ST2" type="com.zhang.pojo.Student">
        <result property="id" column="sid"/>
        <result property="name" column="sname"/>
        <association property="teacher" javaType="com.zhang.pojo.Teacher">
            <result property="name" column="tname"/>
        </association>
    </resultMap>

回顾MySql多对一查询方式:

  • 子查询
  • 联表查询

11、一对多

比如:一个老师拥有多个学生
对于老师而言,就是一对多关系

  1. 环境搭建
    实体类:
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Teacher {
    private int id;
    private String name;
    private List<Student> students;
}
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student {
    private int id;
    private String name;
    private int tid;
}

方式一:按照查询嵌套处理

    <!--按照查询嵌套处理-->
    <select id="getTeacher2" resultMap="TS2">
        select * from teacher where id=#{tid};
    </select>
    <resultMap id="TS2" type="com.zhang.pojo.Teacher">
        <collection property="students" javaType="ArrayList" ofType="com.zhang.pojo.Student" select="getStudent" column="id"/>
    </resultMap>
    <select id="getStudent" resultType="com.zhang.pojo.Student">
        select * from student where tid=#{id};
    </select>

方式二:按照结果嵌套处理

    <!--按照结果嵌套查询-->
    <select id="getTeacher" resultMap="TS">
        select s.id sid,s.name sname,t.id tid,t.name tname from student s,teacher t where t.id=s.tid and t.id=#{tid};
    </select>
    <resultMap id="TS" type="com.zhang.pojo.Teacher">
        <result property="id" column="tid"></result>
        <result property="name" column="tname"></result>
        <!--复杂类型单独处理 对象:assocation 集合:collection
        javaType="":指定属性的类型
        集合中的泛型信息,我们使用ofType获取
        -->
        <collection property="students" ofType="com.zhang.pojo.Student">
            <result property="id" column="sid"/>
            <result property="name" column="sname"/>
            <result property="tid" column="tid"/>
        </collection>
    </resultMap>

小结

  1. 关联:-association【多对一】

  2. 集合:-collection【一对多】

  3. javaType & ofType

     1. javaType用来指定实体类中属性的类型
     2. ofType用来指定映射到List或者集合中的pojo类型,泛型中的约束类型!
    

注意点:

  • 保证SQL的可读性,尽量保证通俗易懂
  • 注意一对多和多对一中,属性名和字段的问题!
  • 如果问题不好排查错误,可以使用日志,建议使用log4j
    MySql引擎
    InnoDB底层原理
    索引
    索引优化

12、动态SQL

什么是动态SQL语句:动态SQL就是根据不同的条件生成不同的SQL语句

如果你之前用过 JSTL 或任何基于类 XML 语言的文本处理器,你对动态 SQL 元素可能会感觉似曾相识。在 MyBatis 之前的版本中,需要花时间了解大量的元素。借助功能强大的基于 OGNL 的表达式,MyBatis 3 替换了之前的大部分元素,大大精简了元素种类,现在要学习的元素种类比原来的一半还要少。

if
choose (when, otherwise)
trim (where, set)
foreach

搭建环境
在这里插入图片描述
创建一个基础工程:

  1. 导包
  2. 编写配置文件
  3. 编写实体类
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Blog {
    private String id;
    private String title;
    private String author;
    private Date createTime;
    private int views;
}
  1. 编写实体类对应Mapper接口和Mapper.xml文件

IF

  1. 接口
    //查询博客
    List<Blog> queryBlogIF(Map map);
  1. Mapper.xml
<select id="queryBlogIF" parameterType="map" resultType="com.zhang.pojo.Blog">
        select * from blog where 1=1
        <if test="title!=null">
            and title =#{title}
        </if>
        <if test="author!=null">
            and author=#{author}
        </if>
    </select>
  1. 测试
@Test
    public void test2(){
        //第一步:获取SqlSession对象
        SqlSession sqlSession= MybatisUtils.getSqlSession();
        //方式一:执行SQL
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
        HashMap map=new HashMap();
        //map.put("title","MyBatis");
        map.put("author","zhang");
        List<Blog> blogs = mapper.queryBlogIF(map);
        for (Blog blog:blogs) {
            System.out.println(blog);
        }
        //关闭SqlSession
        sqlSession.close();
    }

choose(when,otherwise)

  1. 接口
    List<Blog> queryBlogChoose(Map map);
  1. Mapper.xml
<select id="queryBlogChoose" parameterType="map" resultType="com.zhang.pojo.Blog">
        select * from blog
        <where>
            <choose>
                <when test="title!=null">
                    title=#{title}
                </when>
                <when test="author!=null">
                    and author=#{author}
                </when>
                <otherwise>
                    and views=#{views}
                </otherwise>
            </choose>
        </where>
    </select>
  1. 测试
 @Test
    public void test3(){
        //第一步:获取SqlSession对象
        SqlSession sqlSession= MybatisUtils.getSqlSession();
        //方式一:执行SQL
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
        HashMap map=new HashMap();
        map.put("title","MyBatis");
        map.put("author","zhang");
        List<Blog> blogs = mapper.queryBlogChoose(map);
        for (Blog blog:blogs) {
            System.out.println(blog);
        }
        //关闭SqlSession
        sqlSession.close();
    }

Trim(where,set)

  1. 接口
    List<Blog> queryBlogChoose(Map map);
        //更新博客
    int updateBlog(Map map);
  1. Mapper.xml
<select id="queryBlogChoose" parameterType="map" resultType="com.zhang.pojo.Blog">
        select * from blog
        <where>
            <if test="title!=null">
                title =#{title}
            </if>
            <if test="author!=null">
                and author=#{author}
            </if>
        </where>
    </select>
    <update id="updateBlog" parameterType="map">
        update blog
        <set>
            <if test="title!=null">
                title=#{title},
            </if>
            <if test="author!=null">
                author=#{author}
            </if>
        </set>
        where id=#{id}
    </update>
  1. 测试
 @Test
    public void test3(){
        //第一步:获取SqlSession对象
        SqlSession sqlSession= MybatisUtils.getSqlSession();
        //方式一:执行SQL
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
        HashMap map=new HashMap();
        map.put("title","MyBatis");
        map.put("author","zhang");
        List<Blog> blogs = mapper.queryBlogChoose(map);
        for (Blog blog:blogs) {
            System.out.println(blog);
        }
        //关闭SqlSession
        sqlSession.close();
    }
    @Test
    public void test4(){
        //第一步:获取SqlSession对象
        SqlSession sqlSession= MybatisUtils.getSqlSession();
        //方式一:执行SQL
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
        HashMap map=new HashMap();
        map.put("title","MyBatis1");
        map.put("author","zhang1");
        map.put("id","1");
        mapper.updateBlog(map);
        //关闭SqlSession
        sqlSession.close();
    }

SQL片段

有的时候,我们可能会将一些功能的部分抽取出来,方便复用!

  1. 使用SQL标签抽取公共的部分
<sql id="if-title-author">
        <if test="title!=null">
            title =#{title}
        </if>
        <if test="author!=null">
            and author=#{author}
        </if>
</sql>
  1. 在需要使用的地方使用include标签引用即可
    <select id="queryBlogIF" parameterType="map" resultType="com.zhang.pojo.Blog">
        select * from blog
        <where>
            <include refid="if-title-author"></include>
        </where>
    </select>

注意事项:

  • 最好基于单表来定义SQL字段
  • 不要存在where标签

Foreach

    //查询第1-2-3号记录的博客
    List<Blog> queryForeach(Map map);
<select id="queryForeach" parameterType="map" resultType="com.zhang.pojo.Blog">
        select * from blog
        <where>
            <foreach collection="ids" item="id" open="and (" close=")" separator="or">
                id=#{id}
            </foreach>
        </where>
    </select>
@Test
    public void test5(){
        //第一步:获取SqlSession对象
        SqlSession sqlSession= MybatisUtils.getSqlSession();
        //方式一:执行SQL
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
        HashMap map=new HashMap();
        ArrayList<String> ids = new ArrayList<>();
        ids.add("1");
        ids.add("2");
        ids.add("3");
        map.put("ids",ids);
        List<Blog> blogs = mapper.queryForeach(map);
        for (Blog blog:blogs) {
            System.out.print(blog);
        }
        //关闭SqlSession
        sqlSession.close();
    }

所谓的动态SQL,本质还是SQL语句,只是我们可以在SQL层面,去执行一个逻辑代码,动态SQL就是在拼接SQL语句,我们只要保证SQL的正确性,按照SQL的格式,qu排列组合就可以了
建议:

  • 先在MySql中写出完整的SQL,再对应的去修改我们的动态SQL实现通用即可!

13、缓存

查询->连接数据库->耗资源
一次查询的结果暂存在可以直接取到的地方!-->内存:缓存
我们再次查询相同数据的时候,直接走缓存,就不用走数据库了
13.1、简介
  1. 什么是缓存[cache]?
  • 存在内存中的临时数据
  • 将用户经常查询的数据放在缓存(内存)中,用户去查询数据就不用从磁盘上(关系型数据库数据文件)查询,从缓存中查询,从而提高查询效率,解决了高并发系统的性能问题
  1. 为什么要使用缓存?
  • 减少和数据库的交互次数,减少系统开销,提高系统效率
  1. 什么样的数据能使用缓存?
  • 经常查询并且不经常改变的数据
13.2、MyBatis缓存
  • MyBatis包含了一个非常强大的查询缓存特性,他可以非常方便的定制和配置缓存。缓存可以极大的提升查询效率。

  • MyBatis系统中默认定义了两级缓存,一级缓存二级缓存

  • 默认情况下,只有一级缓存开启。(SqlSession级别缓存,也成为本地缓存)

  • 二级缓存需要手动开启和配置,他是基于namespace级别的缓存

  • 为了提高扩展性,MyBatis定义了缓存接口Cache。我们可以通过实现Cache接口来自定义二级缓存

13.3、一级缓存
  • 一级缓存也称为本地缓存

  • 与数据库同一会话期间查询到的数据会放再本地缓存中

  • 以后如果需要获取相同的数据们直接从缓存中拿,没必须再去查询数据库

测试步骤:

  1. 开启日志
  2. 测试在一个Session中查询两次相同记录,查看日志输出
    在这里插入图片描述

缓存失效的情况:

  1. 查询不同的东西

  2. 增删改操作,可能会改变原来的数据,所以必定会刷新缓存
    在这里插入图片描述

  3. 查询不同的Mapper.xml

  4. 手动清理缓存

        sqlSession.clearCache();

小结:一级缓存默认是开启的,只在一次SqlSession中有效,也就是拿到连接到到关闭连接这个区间段

13.4、二级缓存
  • 二级缓存也叫全局缓存,一级缓存作用域太低了,所以诞生了二级缓存。

  • 基于namespace级别缓存,一个名称空间,对应一个二级缓存

  • 工作机制

  • 一个会话查询一条数据,这个数据就会被放在当前会话的一级缓存中

  • 如果当前会话关闭了,这个会话对应的一级缓存就没了,但是我们想要的是,会话关闭了,一级缓存中的数据会被保存到二级缓存中

  • 新的会话查询信息,就可以从二级缓存中获取内容

  • 不同的mapper查出的数据会放在自己对应缓存中
    步骤:

  1. 开启全局缓存
        <!--显示的开启全局缓存-->
        <setting name="cacheEnabled" value="true"/>
  1. 在要使用二级缓存的Mapper中开启
    <!--在当前Mapper.xml中使用二级缓存-->
    <cache/>

也可以自定义一些参数

    <!--在当前Mapper.xml中使用二级缓存-->
    <cache eviction="FIFO" flushInterval="60000" size="512" readOnly="true"/>
  1. 测试

    1. 问题:我们需要实体类序列化!否则就会报错

      Cause: java.io.NotSerializableException: com.zhang.pojo.User
      

小结:

  • 只要开启二级缓存,在同一个Mapper下就有效
  • 所有的数据都会先放在一级缓存中
  • 只有当会话提交,或者关闭的时候,才会提交到二级缓存中
13.5、缓存原理

在这里插入图片描述

13.6、自定义缓存-ehcache###### 13.6、自定义缓存-ehcache
EhCache 是一个纯Java的进程内缓存框架,具有快速、精干等特点,是Hibernate中默认的CacheProvider。Ehcache是一种广泛使用的开源Java分布式缓存。主要面向通用缓存

要在程序中使用ehcache,先要导包!

	<dependency>
            <groupId>org.mybatis.caches</groupId>
            <artifactId>mybatis-ehcache</artifactId>
            <version>1.1.0</version>
	</dependency>

在Mapper指定我们的缓存实现,Mapper.xml文件

    <!--在当前Mapper.xml中使用二级缓存-->
    <cache type="org.mybatis.caches.ehcache.EhcacheCache"/>

resources目录下新建ehcache.xml文件

<?xml version="1.0" encoding="UTF-8" ?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
            updateCheck="false">
    <!--diskStore:缓存数据持久化的目录 地址  -->
    <diskStore path="F:\develop\ehcache" />
    <defaultCache
            eternal="false"
            maxElementsInMemory="10000"
            overflowToDisk="false"
            diskPersistent="false"
            timeToIdleSeconds="1800"
            timeToLiveSeconds="159200"
            memoryStoreEvictionPolicy="LRU"/>
    <cache
            name="cloud_user"
            eternal="false"
            maxElementsInMemory="5000"
            overflowToDisk="false"
            diskPersistent="false"
            timeToIdleSeconds="1800"
            timeToLiveSeconds="1800"
            memoryStoreEvictionPolicy="LRU"/>
</ehcache>

Redis数据库来做缓存!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值