SpringBoot(16)Mybatis与实现分页

打印 上一主题 下一主题

主题 869|帖子 869|积分 2607

1.认识Mybatis

  MyBatis和JPA一样,也是一款优秀的持久层框架,它支持定制化SQL、存储过程,以及高级映射。它可以使用简单的XML或注解来配置和映射原生信息,将接口和Java的POJOs ( Plain Old Java Objects,普通的Java对象)映射成数据库中的记录。
  MyBatis 3提供的注解可以取代XML例如,使用注解@Select直接编写SQL完成数据查询; 使用高级注解@SelectProvider还可以编写动态SQL,以应对复杂的业务需求。
2.Mybatis详细介绍

2.1 CRUD注解

  増加、删除、修改和查询是主要的业务操作,必须掌握这些基础注解的使用方法。MyBatis提供的操作数据的基础注解有以下4个。

  • @Select:用于构建查询语句。
  • @Insert:用于构建添加语句。
  • @Update:用于构建修改语句。
  • @Delete:用于构建删除语句。
  下面来看看它们具体如何使用,见以下代码:
  1. package com.itheima.mapper;
  2. import com.itheima.domain.User;
  3. import org.apache.ibatis.annotations.*;
  4. import org.springframework.data.domain.Page;
  5. import java.util.List;
  6. @Mapper
  7. public interface UserMapper {
  8.     @Select("select * from user where id = #{id}")
  9.     User queryById(@Param("id")int id);
  10.     @Select("select * from user")
  11.     List<User> queryAll();
  12.     @Insert({"insert into user(name,age) values(#{name},#{age})"})
  13.     int add(User user);
  14.     @Delete("delete from user where id = #{id}")
  15.     int delete(int id);
  16.     @Update("update user set name = #{name},age = #{age} where id = #{id}")
  17.     int updateById(User user);
  18.     @Select("select * from user")
  19.     Page<User> getUserList();
  20. }
复制代码
  从上述代码可以看岀:首先要用@Mapper注解来标注类,把UserMapper这个DAO交给 Spring管理。这样Spring会自动生成一个实现类,不用再写UserMapper的映射文件了。最后使用基础的CRUD注解来添加要实现的功能。
2.2 映射注解

MyBatis的映射注解用于建立实体和关系的映射。它有以下3个注解。

  • @Results:用于填写结果集的多个字段的映射关系。
  • @Result:用于填写结果集的单个字段的映射关系,
  • @ResultMap:根据 ID 关联 XML 里面的
  可以在查询SQL的基础上,指定返回的结果集的映射关系。其中,property表示实体对象的属性名,column表示对应的数据库字段名。使用方法见以下代码:
  1. @Results({
  2.         @Result(property = "username",column = "USERNAME"),
  3.         @Result(property = "password",column = "PASSWORD")
  4. })
  5. @Select("select * from user ")
  6. List<User> list();
复制代码
2.3高级注解

  1.高级注解

  MyBatis 3.x版本主要提供了以下4个CRUD的高级注解。

  • @SelectProvider:用于构建动态查询SQL。
  • @lnsertProvider:用于构建动态添加SQL。
  • @UpdateProvider:用于构建动态更新SQL。
  • @DeleteProvider:用于构建动态删除SQL。
  高级注解主要用于编写动态SQL,这里以@SelectProvider为例,它主要包含两个注解属性, 其中,type表示工具类,method表示工具类的某个方法(用于返回具体的SQL )。以下代码可以构建动态SQL,实现查询功能:
  1. package com.itheima.mapper;
  2. import com.itheima.domain.User;
  3. import com.itheima.util.UserSql;
  4. import org.apache.ibatis.annotations.*;
  5. import org.springframework.data.domain.Page;
  6. import java.util.List;
  7. @Mapper
  8. public interface UserMapper {
  9.     @SelectProvider(type = UserSql.class,method = "listAll")
  10.     List<User> listAllUsers();
  11. }
复制代码
  1. package com.itheima.util;
  2. public class UserSql {
  3.     public String listAll(){
  4.         return "SELECT * FROM user";
  5.     }
  6. }
复制代码
  2. MyBatis3注解的用法举例

  (1)如果要查询所有的值,则基础CRUD的代码是:
  1. @Select("select * from user")
  2. List<User> queryAll();
复制代码
  也可以用映射注解来一一映射,见以下代码:
  1. @Select("select * from user")
  2. @Results({
  3.         @Result(property = "id",column = "id"),
  4.         @Result(property = "name",column = "name"),
  5.         @Result(property = "age",column = "age")
  6. })
  7. List<User> listAll();
复制代码
  (2)用多个参数进行查询。
  如果要用多个参数逬行查询,则必须加上注解@Param,否则无法使用EL表达式获取参数.
  1. @Select("select * from user where name like #{name} and age like #{age}")
  2. User getUserByNameAndAge(@Param("name") String name, @Param("age") int age);
复制代码
  还可以根据官方提供的API来编写动态SQL
  1. public static String getUser(@Param("name") String name, @Param("age") int age){
  2.     return new SQL(){{
  3.         SELECT("*");
  4.         FROM("user");
  5.         if (name != null && age != 0){
  6.             WHERE("name like #{name} and age like #{age}");
  7.         }else {
  8.             WHERE("1=2");
  9.         }
  10.     }}.toString();
  11. }
复制代码
  3.实例:用MyBatis实现数据的增加、删除、修改、查询和分页

  (1)创建实体类
  1. @Data
  2. public class User{
  3.     private int id;
  4.     private String name;
  5.     private int age;
  6. }
复制代码
  (2)实现实体和数据表的映射关系
  实现实体和数据表的映射关系可以在Mapper类上添加注解@Mapper,见以下代码。建议以 后直接在入口类加@MapperScan(" com.itheima.mapper"),如果対每个 Mapper 都加注解则很麻烦
  1. package com.itheima.mapper;
  2. import com.itheima.domain.User;
  3. import org.apache.ibatis.annotations.*;
  4. import java.util.List;
  5. @Mapper
  6. public interface UserMapper {
  7.     @Select("select * from user where id = #{id}")
  8.     User queryById(@Param("id")int id);
  9.     @Select("select * from user")
  10.     List<User> queryAll();
  11.     @Insert({"insert into user(name,age) values(#{name},#{age})"})
  12.     int add(User user);
  13.     @Delete("delete from user where id = #{id}")
  14.     int delete(int id);
  15.     @Update("update user set name = #{name},age = #{age} where id = #{id}")
  16.     int updateById(User user);
  17. }
复制代码
3.配置分页功能

  (1)增加分页依赖
  1. <dependency>
  2.     <groupId>com.github.pagehelper</groupId>
  3.     <artifactId>pagehelper</artifactId>
  4.     <version>5.3.1</version>
  5. </dependency>
  6. <dependency>
  7.     <groupId>org.springframework.boot</groupId>
  8.     <artifactId>spring-boot-starter-thymeleaf</artifactId>
  9.     <version>2.0.7.RELEASE</version>
  10. </dependency>
复制代码
  (2)创建分页配置类
  1. package com.itheima.config;
  2. import com.github.pagehelper.PageHelper;
  3. import org.springframework.context.annotation.Bean;
  4. import org.springframework.context.annotation.Configuration;
  5. import java.util.Properties;
  6. @Configuration
  7. public class PageHelperConfig {
  8.     @Bean
  9.     public PageHelper pageHelper(){
  10.         PageHelper pageHelper = new PageHelper();
  11.         Properties properties = new Properties();
  12.         properties.setProperty("offsetAsPageNum","true");
  13.         properties.setProperty("rowBoundsWithCount","true");
  14.         properties.setProperty("reasonable","true");
  15.         pageHelper.setProperties(properties);
  16.         return pageHelper;
  17.     }
  18. }
复制代码
代码解释如下。

  • @Configuration:  表示PageHelperConfig这个类是用来做配置的。
  • @Bean:表示启动PageHelper拦截器。
  • offsetAsPageNum: 当设置为 true 时,会将 RowBounds 第 1 个参数 offset 当成 pageNum (页码)使用。
  • rowBoundsWithCount:当设置为true时,使用RowBounds分页会进行count查询。
  • reasonable :在启用合理化时,如果pageNumpages,则会查询最后一页。
  (3)实现分页控制器

  1.增加分页支持:
  1. <dependency>
  2.     <groupId>com.github.pagehelper</groupId>
  3.     <artifactId>pagehelper-spring-boot-starter</artifactId>
  4.     <version>1.4.3</version>
  5. </dependency>
复制代码
  2.创建分页配置类:
  1. package com.itheima.config;
  2. import com.github.pagehelper.PageHelper;
  3. import org.springframework.context.annotation.Bean;
  4. import org.springframework.context.annotation.Configuration;
  5. import java.util.Properties;
  6. @Configuration
  7. public class PageHelperConfig {
  8.     @Bean
  9.     public PageHelper pageHelper(){
  10.         PageHelper pageHelper = new PageHelper();
  11.         Properties properties = new Properties();
  12.         properties.setProperty("offsetAsPageNum","true");
  13.         properties.setProperty("rowBoundsWithCount","true");
  14.         properties.setProperty("reasonable","true");
  15.         pageHelper.setProperties(properties);
  16.         return pageHelper;
  17.     }
  18. }
复制代码
代码解释如下。

  • @Configuration:表示PageHelperConfig这个类是用来做配置的。
  • @Bean:表示启动PageHelper拦截器。
  • offsetAsPageNum:当设置为 true 时,会将 RowBounds 第 1 个参数 offset 当成 pageNum (页码)使用。
  • rowBoundsWithCount:当设置为true时,使用RowBounds分页会进行count查询。
  • reasonable :在启用合理化时,如果pageNumpages,则会查询最后一页。
  3.实现分页控制器:
  1. package com.itheima.controller;
  2. import com.github.pagehelper.PageHelper;
  3. import com.github.pagehelper.PageInfo;
  4. import com.itheima.domain.User;
  5. import com.itheima.mapper.UserMapper;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.stereotype.Controller;
  8. import org.springframework.ui.Model;
  9. import org.springframework.web.bind.annotation.RequestMapping;
  10. import org.springframework.web.bind.annotation.RequestParam;
  11. import java.util.List;
  12. @Controller
  13. public class UserListController {
  14.     @Autowired
  15.     UserMapper userMapper;
  16.     @RequestMapping("/pagelist")
  17.     public String listCategory(Model model, @RequestParam(value = "start",defaultValue = "1") int start,
  18.                                @RequestParam(value = "size",defaultValue = "20") int size) {
  19.         PageHelper.startPage(start, size,"id desc");
  20.         List<User> users = userMapper.queryAll();
  21.         PageInfo<User> page = new PageInfo<>(users);
  22.         model.addAttribute("page", page);
  23.         return "list";
  24.     }
  25. }
复制代码
代码解释如下。

  • start:在参数里接收当前是第几页。
  • size:每页显示多少条数据。默认值分别是0和20
  • startPage(start,size,"id desc"):根据 start、size 进行分页,并且设置 id 倒排序。
  • List:返回当前分页的集合。
  • Pagelnfo:根据返回的集合创建Pagelnfo対象。
  • addAttribute("page", page):把 page ( Pagelnfo 对象)传递给视图,以供后续显示。
3.比较JPA与Mybatis

1.关注度
JPA在全球范围内的用户数最多,而MyBatis是国内互联网公司的主流选择
2.Hibernate 的优势

  • DAO层开发比MyBatis简单,MyBatis需要维护SQL和结果映射。
  • 对对象的维护和缓存要比MyBatis好,对増加、删除、修改和查询对象的维护更方便。
  • 数据库移植性很好。MyBatis的数据库移植性不好,不同的数据库需要写不同的SQL语句。
  • 有更好的二级缓存机制,可以使用第三方缓存。MyBatis本身提供的缓存机制不佳。
3.MyBatis的优势

  • 可以进行更为细致的SQL优化,可以减少查询字段(大部分人这么认为,但是实际上 Hibernate —样可以实现)。
  • 容易掌握。Hibernate门槛较高(大部分人都这么认为)
4.简单总结

  • MyBatis:小巧、方便、高效、简单、直接、半自动化。
  • Hibernate:强大、方便、高效、复杂、间接、全自动化。
它们各自的缺点都可以依据各目更深入的技术方案来解决。所以,笔者的建议是:

  • 如果没有SQL语言的基础,则建议使用JPA。
  • 如果有SQL语言基础,则建议使用MyBatis,因为国内使用MyBatis的人比使用JPA的人多很多。
 

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

小秦哥

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表