Mybatis与实现分页- SpringBoot(16)
|字数总计:2.4k|阅读时长:11分钟|阅读量:
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:用于构建删除语句。
下面来看看它们具体如何使用,见以下代码:
package com.itheima.mapper;
import com.itheima.domain.User; import org.apache.ibatis.annotations.*; import org.springframework.data.domain.Page; import java.util.List;
@Mapper public interface UserMapper { @Select("select * from user where id = #{id}") User queryById(@Param("id")int id);
@Select("select * from user") List<User> queryAll();
@Insert({"insert into user(name,age) values(#{name},#{age})"}) int add(User user);
@Delete("delete from user where id = #{id}") int delete(int id);
@Update("update user set name = #{name},age = #{age} where id = #{id}") int updateById(User user);
@Select("select * from user") Page<User> getUserList(); }
|
从上述代码可以看岀:首先要用@Mapper注解来标注类,把UserMapper这个DAO交给 Spring管理。这样Spring会自动生成一个实现类,不用再写UserMapper的映射文件了。最后使用基础的CRUD注解来添加要实现的功能。
2.2 映射注解
MyBatis的映射注解用于建立实体和关系的映射。它有以下3个注解。
- @Results:用于填写结果集的多个字段的映射关系。
- @Result:用于填写结果集的单个字段的映射关系,
- @ResultMap:根据 ID 关联 XML 里面的
可以在查询SQL的基础上,指定返回的结果集的映射关系。其中,property表示实体对象的属性名,column表示对应的数据库字段名。使用方法见以下代码:
@Results({ @Result(property = "username",column = "USERNAME"), @Result(property = "password",column = "PASSWORD")
}) @Select("select * from user ") 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,实现查询功能:
package com.itheima.mapper;
import com.itheima.domain.User; import com.itheima.util.UserSql; import org.apache.ibatis.annotations.*; import org.springframework.data.domain.Page; import java.util.List;
@Mapper public interface UserMapper { @SelectProvider(type = UserSql.class,method = "listAll") List<User> listAllUsers(); }
|
package com.itheima.util;
public class UserSql { public String listAll(){ return "SELECT * FROM user"; } }
|
2. MyBatis3注解的用法举例
(1)如果要查询所有的值,则基础CRUD的代码是:
@Select("select * from user") List<User> queryAll();
|
也可以用映射注解来一一映射,见以下代码:
@Select("select * from user") @Results({ @Result(property = "id",column = "id"), @Result(property = "name",column = "name"), @Result(property = "age",column = "age") }) List<User> listAll();
|
(2)用多个参数进行查询。
如果要用多个参数逬行查询,则必须加上注解@Param,否则无法使用EL表达式获取参数.
@Select("select * from user where name like #{name} and age like #{age}") User getUserByNameAndAge(@Param("name") String name, @Param("age") int age);
|
还可以根据官方提供的API来编写动态SQL
public static String getUser(@Param("name") String name, @Param("age") int age){ return new SQL(){{ SELECT("*"); FROM("user"); if (name != null && age != 0){ WHERE("name like #{name} and age like #{age}"); }else { WHERE("1=2"); } }}.toString(); }
|
3.实例:用MyBatis实现数据的增加、删除、修改、查询和分页
(1)创建实体类
@Data public class User{ private int id; private String name; private int age; }
|
(2)实现实体和数据表的映射关系
实现实体和数据表的映射关系可以在Mapper类上添加注解@Mapper,见以下代码。建议以 后直接在入口类加@MapperScan(“ com.itheima.mapper”),如果対每个 Mapper 都加注解则很麻烦
package com.itheima.mapper;
import com.itheima.domain.User; import org.apache.ibatis.annotations.*; import java.util.List;
@Mapper public interface UserMapper { @Select("select * from user where id = #{id}") User queryById(@Param("id")int id);
@Select("select * from user") List<User> queryAll();
@Insert({"insert into user(name,age) values(#{name},#{age})"}) int add(User user);
@Delete("delete from user where id = #{id}") int delete(int id);
@Update("update user set name = #{name},age = #{age} where id = #{id}") int updateById(User user); }
|
3.配置分页功能
(1)增加分页依赖
<dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper-spring-boot-starter</artifactId> <version>1.4.3</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> <version>2.0.7.RELEASE</version> </dependency>
|
(2)创建分页配置类
package com.itheima.config;
import com.github.pagehelper.PageHelper; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.util.Properties;
@Configuration public class PageHelperConfig { @Bean public PageHelper pageHelper(){ PageHelper pageHelper = new PageHelper(); Properties properties = new Properties(); properties.setProperty("offsetAsPageNum","true"); properties.setProperty("rowBoundsWithCount","true"); properties.setProperty("reasonable","true"); pageHelper.setProperties(properties); return pageHelper; } }
|
代码解释如下。
- @Configuration: 表示PageHelperConfig这个类是用来做配置的。
- @Bean:表示启动PageHelper拦截器。
- offsetAsPageNum: 当设置为 true 时,会将 RowBounds 第 1 个参数 offset 当成 pageNum (页码)使用。
- rowBoundsWithCount:当设置为true时,使用RowBounds分页会进行count查询。
- reasonable :在启用合理化时,如果pageNum<1 ,则会查询第一页;如果 pageNum>pages,则会查询最后一页。
(3)实现分页控制器
1.实现分页控制器:
package com.itheima.controller;
import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import com.itheima.domain.User; import com.itheima.mapper.UserMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import java.util.List;
@Controller public class UserListController { @Autowired UserMapper userMapper; @RequestMapping("/pagelist") public String listCategory(Model model, @RequestParam(value = "start",defaultValue = "1") int start, @RequestParam(value = "size",defaultValue = "20") int size) { PageHelper.startPage(start, size,"id desc"); List<User> users = userMapper.queryAll(); PageInfo<User> page = new PageInfo<>(users); model.addAttribute("page", page); return "list"; } }
|
代码解释如下。
- start:在参数里接收当前是第几页。
- size:每页显示多少条数据。默认值分别是0和20
- startPage(start,size,”id desc”):根据 start、size 进行分页,并且设置 id 倒排序。
- List:返回当前分页的集合。
- Pagelnfo:根据返回的集合创建Pagelnfo対象。
- addAttribute(“page”, page):把 page ( Pagelnfo 对象)传递给视图,以供后续显示。
2.创建分页视图:
<!DOCTYPE html> <html lang="en" xmlns="https://www.w3.org/1999/xhtml" xmlns:th="https://www.thymeleaf.org" xmlns:sec="https://www.thymeleaf.org/tyemeleaf-extras-springsecurity5"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div th:each="u:${page.list}"> <span scope = "row" th:text="${u.id}">id</span> <span th:text="${u.name}">name</span> </div> <div> <a th:href="@{pagelist?start=1}">[首页]</a> <a th:if="${not page.isFirstPage}" th:href="@{/pagelist(start=${page.pageNum-1})}">[上页]</a> <a th:if="${not page.isLastPage}" th:href="@{/pagelist(start=${page.pageNum+1})}">[下页]</a> <a th:href="@{/pagelist(start=${page.pages})}">[末页]</a> <div> 当前页/总页数:<a th:text="${page.pageNum}" th:href="@{pagelist(start=${page.pageNum})}"></a> /<a th:text="${page.pages}" th:href="@{/pagelist(start=${page.pages})}"></a> </div> </div> </body> </html>
|
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的人多很多。