Springboot集成mybatis通用Mapper与分页插件PageHelper(推荐)
插件介绍
通用 Mapper 是一个可以实现任意 MyBatis 通用方法的框架,项目提供了常规的增删改查操作以及 Example
相关的单表操作。通用 Mapper 是为了解决 MyBatis 使用中 90% 的基本操作,PageHelper则提供通用的分页查询功能,使用它们可以很方便的进行开发,可以节省开发人员大量的时间。
通用Mapper的GIT地址: https://gitee.com/free/Mapper
分页插件的GIT地址: https://github.com/pagehelper/Mybatis-PageHelper
项目结构
导入依赖
<!-- 通用Mapper插件 文档地址:https://gitee.com/free/Mapper/wikis/Home --> <dependency> <groupId>tk.mybatis</groupId> <artifactId>mapper-spring-boot-starter</artifactId> <version>2.1.5</version> </dependency> <!-- 分页插件 文档地址:https://github.com/pagehelper/Mybatis-PageHelper/blob/master/wikis/zh/HowToUse.md --> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper-spring-boot-starter</artifactId> <version>1.2.10</version> </dependency> <!-- MYSQL包 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <!-- 默认就内嵌了Tomcat 容器,如需要更换容器也极其简单--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
属性配置
在 application.properties
文件中分别添加上数据库、Mybatis、通用Mapper、PageHelper的属性配置
spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true&useSSL=false spring.datasource.username=root spring.datasource.password=123456 # 如果想看到mybatis日志需要做如下配置 logging.level.com.carry=DEBUG ######### Mybatis 自身配置 ########## mybatis.mapper-locations=classpath:com/carry/mapper/*Mapper.xml mybatis.type-aliases-package=com.carry.entity # 驼峰命名规范 如:数据库字段是 order_id 那么 实体字段就要写成 orderId mybatis.configuration.map-underscore-to-camel-case=true######### 通用Mapper ########## # 主键自增回写方法,默认值MYSQL,详细说明请看文档 mapper.identity=MYSQL mapper.mappers=tk.mybatis.mapper.common.Mapper # 设置 insert 和 update 中,是否判断字符串类型!=‘‘ mapper.not-empty=true # 枚举按简单类型处理 mapper.enum-as-simple-type=true ######### 分页插件 ########## pagehelper.helper-dialect=mysql pagehelper.params=count=countSql pagehelper.reasonable=false pagehelper.support-methods-arguments=true
通用Mapper:
- mapper.enum-as-simple-type: 枚举按简单类型处理,如果有枚举字段则需要加上该配置才会做映射
- mapper.not-empty: 设置以后,会去判断 insert 和 update 中符串类型!=‘‘
分页插件:
- pagehelper.reasonable: 分页合理化参数,默认值为false。当该参数设置为 true 时,pageNum<=0 时会查询第一页, pageNum>pages(超过总数时),会查询最后一页。默认false 时,直接根据参数进行查询
- support-methods-arguments: 支持通过 Mapper 接口参数来传递分页参数,默认值false,分页插件会从查询方法的参数值中,自动根据上面 params 配置的字段中取值,查找到合适的值时就会自动分页
注意事项:
由于 mybatis.mapper-locations=classpath:com/carry/mapper/*.xml配置的在java package
中,而Spring Boot
默认只打入java package -> *.java
,所以我们需要给pom.xml
文件添加如下内容
<build> <resources> <resource> <directory>src/main/resources</directory> </resource> <resource> <directory>src/main/java</directory> <includes> <include>**/*.xml</include> </includes> <filtering>true</filtering> </resource> </resources> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build>
具体编码
1、表结构
创建一张 user
表
1 2 3 4 5 6 | CREATE TABLE ` user ` ( `id` int (8) NOT NULL AUTO_INCREMENT COMMENT ‘主键自增‘ , `username` varchar (50) NOT NULL COMMENT ‘用户名‘ , ` password ` varchar (50) NOT NULL COMMENT ‘密码‘ , PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT= ‘用户表‘ ; |
2、实体类
package com.carry.entity; import java.io.Serializable; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @Table(name = "user") public class User implements Serializable { private static final long serialVersionUID = -8057591359892731452L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String username; private String password; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public User() {} public User(String username, String password) { super(); this.username = username; this.password = password; } }
3、持久层
package com.carry.mapper; import com.carry.entity.User; import tk.mybatis.mapper.common.Mapper;
public interface UserMapper extends Mapper<User> { /** * 根据用户名统计(假设它是一个很复杂的SQL) * @param username 用户名 * @return 统计结果 */ int countByUsername(String username); }
4、映射文件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.carry.mapper.UserMapper"> <select id="countByUsername" resultType="java.lang.Integer"> SELECT count(1) FROM user WHERE username = #{username} </select> </mapper>
5、启动类
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import tk.mybatis.spring.annotation.MapperScan; @SpringBootApplication @MapperScan(basePackages = "com.carry.mapper") public class SpringbootMapperPagehelperApplication { public static void main(String[] args) { SpringApplication.run(SpringbootMapperPagehelperApplication.class, args); } }
测试
完成数据访问层接口后,编写一个junit
测试类来检验代码的正确性。
package com.carry; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import com.carry.entity.User; import com.carry.mapper.UserMapper; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; @RunWith(SpringRunner.class) @SpringBootTest public class SpringbootMapperPagehelperApplicationTests { private final Logger logger = LoggerFactory.getLogger(this.getClass()); @Autowired private UserMapper userMapper; @Test public void test() { try { final User user1 = new User("u1", "p1"); final User user2 = new User("u1", "p2"); final User user3 = new User("u3", "p3"); userMapper.insertSelective(user1); logger.info("[user1回写主键] - [{}]", user1.getId()); userMapper.insertSelective(user2); logger.info("[user2回写主键] - [{}]", user2.getId()); userMapper.insertSelective(user3); logger.info("[user3回写主键] - [{}]", user3.getId()); final int count = userMapper.countByUsername("u1"); logger.info("[调用自己写的SQL] - [{}]", count); // TODO 模拟分页 for (int i = 0; i < 20; i++) { userMapper.insertSelective(new User("u" + i, "p" + i)); } // TODO 分页 + 排序 this.userMapper.selectAll() 这一句就是我们需要写的查询,有了这两款插件无缝切换各种数据库 final PageInfo<User> pageInfo = PageHelper.startPage(1, 10).setOrderBy("id desc") .doSelectPageInfo(() -> this.userMapper.selectAll()); logger.info("[lambda写法] - [分页信息] - [{}]", pageInfo.toString()); PageHelper.startPage(1, 10).setOrderBy("id desc"); final PageInfo<User> userPageInfo = new PageInfo<>(this.userMapper.selectAll()); logger.info("[普通写法] - [{}]", userPageInfo); } catch (Exception e) { logger.error(e.getMessage()); } } }
相关推荐
xiuyangsong 2020-06-03
smalllove 2020-05-09
Dullonjiang 2020-05-06
zhiyuan0 2020-02-20
无情的你无情的雨 2020-02-18
kevincheung 2020-02-15
dongxurr 2020-01-29
flydoging 2020-01-23
javamagicsun 2019-12-07
韩学敏 2019-11-09
XCMercy 2019-10-29
javamagicsun 2019-09-21
javamagicsun 2019-07-01
shushan 2015-11-28
kevincheung 2015-04-07
jackuseradmin 2019-06-28
javamagicsun 2019-06-27
zhiyuan0 2019-06-04
jackuseradmin 2019-01-11