SpringBoot+SpringMVC+MybatisPlus框架整合实现分页插件查询

1、首先介绍一下,mybatisPlus

根据官方文档的介绍,MybatisPlus(简称mp)是对mybatis的增强而不做改变,只为ti提高效率简化开发,具体参见http://mp.baomidou.com/#/?id=%e7%ae%80%e4%bb%8b

2.项目结构

3.框架搭建

打开Eclipse->File->New->springboot->spring starter project 选择Type为maven

4.创建成功之后,配置pom.xml文件和application.yml文件

<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.2.0.M1</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.example</groupId> <artifactId>Springboot-mybatisPlus</artifactId> <version>0.0.1-SNAPSHOT</version> <name>Springboot-mybatisPlus</name> <description>Demo project for Spring Boot</description>

<properties> <java.version>1.8</java.version> </properties>

<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>

<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency>

<!-- mybatis-plus begin --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatisplus-spring-boot-starter</artifactId> <version>1.0.5</version> </dependency> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus</artifactId> <version>2.2.0</version> </dependency> <!-- mybatis-plus end --> <!-- 引入Druid依赖,阿里巴巴所提供的数据源 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.0.29</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.16.16</version> </dependency>

<!-- 模板引擎 -->

<dependency> <groupId>org.apache.velocity</groupId> <artifactId>velocity-engine-core</artifactId> <version>2.0</version> </dependency> </dependencies>

<build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build>

<repositories> <repository> <id>spring-snapshots</id> <name>Spring Snapshots</name> <url>https://repo.spring.io/snapshot</url> <snapshots> <enabled>true</enabled> </snapshots> </repository> <repository> <id>spring-milestones</id> <name>Spring Milestones</name> <url>https://repo.spring.io/milestone</url> </repository> </repositories> <pluginRepositories> <pluginRepository> <id>spring-snapshots</id> <name>Spring Snapshots</name> <url>https://repo.spring.io/snapshot</url> <snapshots> <enabled>true</enabled> </snapshots> </pluginRepository> <pluginRepository> <id>spring-milestones</id> <name>Spring Milestones</name> <url>https://repo.spring.io/milestone</url> </pluginRepository> </pluginRepositories>

</project> 5.application.yml

# 该配置的名称是固定的,不可以改变,否则将不能自动加载到数据源中 spring: datasource: # 使用druid数据源 type: com.alibaba.druid.pool.DruidDataSource driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://127.0.0.1:9306/wise_secretgarden?useUnicode=true&characterEncoding=utf-8 username: admin password: admin validation-query: "SELECT 'X' FROM DUAL" max-wait: 10000 #最大建立连接等待时间。如果超过此时间将接到异常。设为-1表示无限制 max-idle: 10 #最大空闲数,数据库连接的最大空闲时间。超过空闲时间,数据库连接将被释放。设为0表示无限制 min-idle: 5 ##最小空闲连接:连接池中容许保持空闲状态的最小连接数量,低于这个数量将创建新的连接 max_active: 50 ##连接池的最大数据库连接数。设为0表示无限制 initial-size: 5 #初始化连接:连接池启动时创建的初始化连接数量 test-on-borrow: false test-while-idle: true remove_abandoned: true #超过removeAbandonedTimeout时间后,是否进 行没用连接(废弃)的回收(默认为false,调整为true) remove_abandoned_timeout: 180 #超过时间限制,回收没有用(废弃)的连接(默认为 300秒,调整为180) time-between-eviction-runs-millis: 18800 pool-prepared-statements: true max-pool-prepared-statement-per-connection-size: 20 connection-properties: config.decrypt=true;druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000 filters: stat,wall,log4j2 mybatis-plus: mapper-locations: classpath:/mapper/*.xml #实体扫描,多个package用逗号或者分号分隔 typeAliasesPackage: com.example.demo.model

6.mybatis-plus配置-MybatisPlusConfig.java

package com.example.demo.config;

import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration;

import com.baomidou.mybatisplus.plugins.PaginationInterceptor;

@Configuration

public class MybatisPlusConfig { /** * mybatis-plus分页插件<br> */ @Bean public PaginationInterceptor paginationInterceptor() { return new PaginationInterceptor(); }

} 7.使用mybatis-plus的代码生成插件

package com.example.demo.util;

import java.util.HashMap; import java.util.Map;

import com.baomidou.mybatisplus.generator.AutoGenerator; import com.baomidou.mybatisplus.generator.InjectionConfig; import com.baomidou.mybatisplus.generator.config.DataSourceConfig; import com.baomidou.mybatisplus.generator.config.GlobalConfig; import com.baomidou.mybatisplus.generator.config.PackageConfig; import com.baomidou.mybatisplus.generator.config.StrategyConfig; import com.baomidou.mybatisplus.generator.config.converts.MySqlTypeConvert; import com.baomidou.mybatisplus.generator.config.rules.DbColumnType; import com.baomidou.mybatisplus.generator.config.rules.DbType; import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;

import lombok.extern.slf4j.Slf4j;

@Slf4j public class MpGenerator { public static void main(String[] args) { AutoGenerator mpg = new AutoGenerator(); // 全局配置 GlobalConfig gc = new GlobalConfig(); gc.setOutputDir("D:/source"); gc.setFileOverride(true); gc.setActiveRecord(true); gc.setEnableCache(false);// XML 二级缓存 gc.setBaseResultMap(true);// XML ResultMap gc.setBaseColumnList(false);// XML columList gc.setAuthor("the_sardine"); mpg.setGlobalConfig(gc); // 数据源配置 DataSourceConfig dsc = new DataSourceConfig(); dsc.setDbType(DbType.MYSQL); dsc.setTypeConvert(new MySqlTypeConvert() { // 自定义数据库表字段类型转换【可选】 @Override public DbColumnType processTypeConvert(String fieldType) { log.info("转换类型:" + fieldType); // 注意!!processTypeConvert 存在默认类型转换,如果不是你要的效果请自定义返回、非如下直接返回。 return super.processTypeConvert(fieldType); } }); dsc.setDriverName("com.mysql.jdbc.Driver"); dsc.setUsername("admin"); dsc.setPassword("admin"); dsc.setUrl("jdbc:mysql://127.0.0.1:9306/wise_secretgarden?useUnicode=true&characterEncoding=utf-8"); mpg.setDataSource(dsc); // 策略配置 StrategyConfig strategy = new StrategyConfig(); strategy.setNaming(NamingStrategy.underline_to_camel);// 表名生成策略 strategy.setExclude("coach"); mpg.setStrategy(strategy); // 包配置 PackageConfig pc = new PackageConfig(); pc.setParent(null); pc.setEntity("com.example.demo.model"); pc.setMapper("com.example.demo.mapper"); pc.setService("com.example.demo.service"); pc.setServiceImpl("com.example.demo.service.impl"); pc.setController("com.example.demo.controller"); mpg.setPackageInfo(pc); // 注入自定义配置,可以在 VM 中使用 cfg.abc 【可无】 InjectionConfig cfg = new InjectionConfig() { @Override public void initMap() { Map<String, Object> map = new HashMap<>(); map.put("abc", this.getConfig().getGlobalConfig().getAuthor() + "-mp"); this.setMap(map); } }; mpg.setCfg(cfg); mpg.execute(); // 打印注入设置【可无】 log.error("error", mpg.getCfg().getMap().get("abc")); } }

执行代码后会生成如下结构:

将相应模块代码稍微修改下,放入项目就可以了

8.代码示例

Coach.java

package com.example.demo.model;

import java.util.Date; import com.baomidou.mybatisplus.activerecord.Model; import java.io.Serializable;

/** * <p> * 教练表 * </p> * * @author the_sardine * @since 2019-04-08 */ public class Coach extends Model<Coach> {

private static final long serialVersionUID = 1L;

private String id; private String lang; private Integer state; private String name; private String url; private String levelText; private String levelCode; private String coachCode; private String context; private String sex; private String birth; private String teachAge; private String skiAge; private String idNumber; private String phoneNumber; private String email; private Integer enableSingleSki; private Integer enableDoubleSki; private String peopleNum; private String introduction; private String money; private String training; private String trainingTime; private String area; private Date createTime; private String createUserId; private Date lastModifyTime; private String lastModifyUserId;

public String getId() { return id; }

public void setId(String id) { this.id = id; }

public String getLang() { return lang; }

public void setLang(String lang) { this.lang = lang; }

public Integer getState() { return state; }

public void setState(Integer state) { this.state = state; }

public String getName() { return name; }

public void setName(String name) { this.name = name; }

public String getUrl() { return url; }

public void setUrl(String url) { this.url = url; }

public String getLevelText() { return levelText; }

public void setLevelText(String levelText) { this.levelText = levelText; }

public String getLevelCode() { return levelCode; }

public void setLevelCode(String levelCode) { this.levelCode = levelCode; }

public String getCoachCode() { return coachCode; }

public void setCoachCode(String coachCode) { this.coachCode = coachCode; }

public String getContext() { return context; }

public void setContext(String context) { this.context = context; }

public String getSex() { return sex; }

public void setSex(String sex) { this.sex = sex; }

public String getBirth() { return birth; }

public void setBirth(String birth) { this.birth = birth; }

public String getTeachAge() { return teachAge; }

public void setTeachAge(String teachAge) { this.teachAge = teachAge; }

public String getSkiAge() { return skiAge; }

public void setSkiAge(String skiAge) { this.skiAge = skiAge; }

public String getIdNumber() { return idNumber; }

public void setIdNumber(String idNumber) { this.idNumber = idNumber; }

public String getPhoneNumber() { return phoneNumber; }

public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; }

public String getEmail() { return email; }

public void setEmail(String email) { this.email = email; }

public Integer getEnableSingleSki() { return enableSingleSki; }

public void setEnableSingleSki(Integer enableSingleSki) { this.enableSingleSki = enableSingleSki; }

public Integer getEnableDoubleSki() { return enableDoubleSki; }

public void setEnableDoubleSki(Integer enableDoubleSki) { this.enableDoubleSki = enableDoubleSki; }

public String getPeopleNum() { return peopleNum; }

public void setPeopleNum(String peopleNum) { this.peopleNum = peopleNum; }

public String getIntroduction() { return introduction; }

public void setIntroduction(String introduction) { this.introduction = introduction; }

public String getMoney() { return money; }

public void setMoney(String money) { this.money = money; }

public String getTraining() { return training; }

public void setTraining(String training) { this.training = training; }

public String getTrainingTime() { return trainingTime; }

public void setTrainingTime(String trainingTime) { this.trainingTime = trainingTime; }

public String getArea() { return area; }

public void setArea(String area) { this.area = area; }

public Date getCreateTime() { return createTime; }

public void setCreateTime(Date createTime) { this.createTime = createTime; }

public String getCreateUserId() { return createUserId; }

public void setCreateUserId(String createUserId) { this.createUserId = createUserId; }

public Date getLastModifyTime() { return lastModifyTime; }

public void setLastModifyTime(Date lastModifyTime) { this.lastModifyTime = lastModifyTime; }

public String getLastModifyUserId() { return lastModifyUserId; }

public void setLastModifyUserId(String lastModifyUserId) { this.lastModifyUserId = lastModifyUserId; }

@Override protected Serializable pkVal() { return this.id; }

@Override public String toString() { return "Coach{" + ", id=" + id + ", lang=" + lang + ", state=" + state + ", name=" + name + ", url=" + url + ", levelText=" + levelText + ", levelCode=" + levelCode + ", coachCode=" + coachCode + ", context=" + context + ", sex=" + sex + ", birth=" + birth + ", teachAge=" + teachAge + ", skiAge=" + skiAge + ", idNumber=" + idNumber + ", phoneNumber=" + phoneNumber + ", email=" + email + ", enableSingleSki=" + enableSingleSki + ", enableDoubleSki=" + enableDoubleSki + ", peopleNum=" + peopleNum + ", introduction=" + introduction + ", money=" + money + ", training=" + training + ", trainingTime=" + trainingTime + ", area=" + area + ", createTime=" + createTime + ", createUserId=" + createUserId + ", lastModifyTime=" + lastModifyTime + ", lastModifyUserId=" + lastModifyUserId + "}"; } }

CoachMapper.java

package com.example.demo.mapper;

import com.baomidou.mybatisplus.mapper.BaseMapper; import com.example.demo.model.Coach;

/** * <p> * 教练表 Mapper 接口 * </p> * * @author the_sardine * @since 2019-04-08 */ public interface CoachMapper extends BaseMapper<Coach> { }

打开你会发现mapper里面是空的,那是因为mybatis-plus已经帮我们把一些常用的通用的增删改查的代码,还有对分页查询的处理全都封装在BaseMapper里了,简化了我们的开发代码量。

package com.baomidou.mybatisplus.mapper;

import java.io.Serializable; import java.util.Collection; import java.util.List; import java.util.Map;

import org.apache.ibatis.annotations.Param; import org.apache.ibatis.session.RowBounds;

/** * <p> * Mapper 继承该接口后,无需编写 mapper.xml 文件,即可获得CRUD功能 * </p> * <p> * 这个 Mapper 支持 id 泛型 * </p> * * @author hubin * @Date 2016-01-23 */ public interface BaseMapper<T> {

/** * <p> * 插入一条记录 * </p> * * @param entity 实体对象 * @return int */ Integer insert(T entity);

/** * <p> * 插入一条记录 * </p> * * @param entity 实体对象 * @return int */ Integer insertAllColumn(T entity);

/** * <p> * 根据 ID 删除 * </p> * * @param id 主键ID * @return int */ Integer deleteById(Serializable id);

/** * <p> * 根据 columnMap 条件,删除记录 * </p> * * @param columnMap 表字段 map 对象 * @return int */ Integer deleteByMap(@Param("cm") Map<String, Object> columnMap);

/** * <p> * 根据 entity 条件,删除记录 * </p> * * @param wrapper 实体对象封装操作类(可以为 null) * @return int */ Integer delete(@Param("ew") Wrapper<T> wrapper);

/** * <p> * 删除(根据ID 批量删除) * </p> * * @param idList 主键ID列表 * @return int */ Integer deleteBatchIds(@Param("coll") Collection<? extends Serializable> idList);

/** * <p> * 根据 ID 修改 * </p> * * @param entity 实体对象 * @return int */ Integer updateById(@Param("et") T entity);

/** * <p> * 根据 ID 修改 * </p> * * @param entity 实体对象 * @return int */ Integer updateAllColumnById(@Param("et") T entity);

/** * <p> * 根据 whereEntity 条件,更新记录 * </p> * * @param entity 实体对象 * @param wrapper 实体对象封装操作类(可以为 null) * @return */ Integer update(@Param("et") T entity, @Param("ew") Wrapper<T> wrapper);

/** * <p> * 根据 ID 查询 * </p> * * @param id 主键ID * @return T */ T selectById(Serializable id);

/** * <p> * 查询(根据ID 批量查询) * </p> * * @param idList 主键ID列表 * @return List<T> */ List<T> selectBatchIds(@Param("coll") Collection<? extends Serializable> idList);

/** * <p> * 查询(根据 columnMap 条件) * </p> * * @param columnMap 表字段 map 对象 * @return List<T> */ List<T> selectByMap(@Param("cm") Map<String, Object> columnMap);

/** * <p> * 根据 entity 条件,查询一条记录 * </p> * * @param entity 实体对象 * @return T */ T selectOne(@Param("ew") T entity);

/** * <p> * 根据 Wrapper 条件,查询总记录数 * </p> * * @param wrapper 实体对象 * @return int */ Integer selectCount(@Param("ew") Wrapper<T> wrapper);

/** * <p> * 根据 entity 条件,查询全部记录 * </p> * * @param wrapper 实体对象封装操作类(可以为 null) * @return List<T> */ List<T> selectList(@Param("ew") Wrapper<T> wrapper);

/** * <p> * 根据 Wrapper 条件,查询全部记录 * </p> * * @param wrapper 实体对象封装操作类(可以为 null) * @return List<T> */ List<Map<String, Object>> selectMaps(@Param("ew") Wrapper<T> wrapper);

/** * <p> * 根据 Wrapper 条件,查询全部记录 * 注意: 只返回第一个字段的值 * </p> * * @param wrapper 实体对象封装操作类(可以为 null) * @return List<Object> */ List<Object> selectObjs(@Param("ew") Wrapper<T> wrapper);

/** * <p> * 根据 entity 条件,查询全部记录(并翻页) * </p> * * @param rowBounds 分页查询条件(可以为 RowBounds.DEFAULT) * @param wrapper 实体对象封装操作类(可以为 null) * @return List<T> */ List<T> selectPage(RowBounds rowBounds, @Param("ew") Wrapper<T> wrapper);

/** * <p> * 根据 Wrapper 条件,查询全部记录(并翻页) * </p> * * @param rowBounds 分页查询条件(可以为 RowBounds.DEFAULT) * @param wrapper 实体对象封装操作类 * @return List<Map<String, Object>> */ List<Map<String, Object>> selectMapsPage(RowBounds rowBounds, @Param("ew") Wrapper<T> wrapper);

} ICoachService.java

package com.example.demo.service;

import com.example.demo.model.Coach; import com.baomidou.mybatisplus.service.IService;

/** * <p> * 教练表 服务类 * </p> * * @author the_sardine * @since 2019-04-08 */ public interface ICoachService extends IService<Coach> {

}

package com.baomidou.mybatisplus.service;

import java.io.Serializable; import java.util.Collection; import java.util.List; import java.util.Map;

import com.baomidou.mybatisplus.mapper.Wrapper; import com.baomidou.mybatisplus.plugins.Page;

/** * <p> * 顶级 Service * </p> * * @author hubin * @Date 2016-04-20 */ public interface IService<T> {

/** * <p> * 插入一条记录(选择字段,策略插入) * </p> * * @param entity 实体对象 * @return boolean */ boolean insert(T entity);

/** * <p> * 插入一条记录(全部字段) * </p> * * @param entity 实体对象 * @return boolean */ boolean insertAllColumn(T entity);

/** * <p> * 插入(批量),该方法不适合 Oracle * </p> * * @param entityList 实体对象列表 * @return boolean */ boolean insertBatch(List<T> entityList);

/** * <p> * 插入(批量) * </p> * * @param entityList 实体对象列表 * @param batchSize 插入批次数量 * @return boolean */ boolean insertBatch(List<T> entityList, int batchSize);

/** * <p> * 批量修改插入 * </p> * * @param entityList 实体对象列表 * @return boolean */ boolean insertOrUpdateBatch(List<T> entityList);

/** * <p> * 批量修改插入 * </p> * * @param entityList 实体对象列表 * @param batchSize * @return boolean */ boolean insertOrUpdateBatch(List<T> entityList, int batchSize);

/** * <p> * 批量修改或插入全部字段 * </p> * * @param entityList 实体对象列表 * @return boolean */ boolean insertOrUpdateAllColumnBatch(List<T> entityList);

/** * 批量修改或插入全部字段 * * @param entityList 实体对象列表 * @param batchSize * @return boolean */ boolean insertOrUpdateAllColumnBatch(List<T> entityList, int batchSize);

/** * <p> * 根据 ID 删除 * </p> * * @param id 主键ID * @return boolean */ boolean deleteById(Serializable id);

/** * <p> * 根据 columnMap 条件,删除记录 * </p> * * @param columnMap 表字段 map 对象 * @return boolean */ boolean deleteByMap(Map<String, Object> columnMap);

/** * <p> * 根据 entity 条件,删除记录 * </p> * * @param wrapper 实体包装类 {@link Wrapper} * @return boolean */ boolean delete(Wrapper<T> wrapper);

/** * <p> * 删除(根据ID 批量删除) * </p> * * @param idList 主键ID列表 * @return boolean */ boolean deleteBatchIds(Collection<? extends Serializable> idList);

/** * <p> * 根据 ID 选择修改 * </p> * * @param entity 实体对象 * @return boolean */ boolean updateById(T entity);

/** * <p> * 根据 ID 修改全部字段 * </p> * * @param entity 实体对象 * @return boolean */ boolean updateAllColumnById(T entity);

/** * <p> * 根据 whereEntity 条件,更新记录 * </p> * * @param entity 实体对象 * @param wrapper 实体包装类 {@link Wrapper} * @return boolean */ boolean update(T entity, Wrapper<T> wrapper);

/** * <p> * 根据ID 批量更新 * </p> * * @param entityList 实体对象列表 * @return boolean */ boolean updateBatchById(List<T> entityList);

/** * <p> * 根据ID 批量更新 * </p> * * @param entityList 实体对象列表 * @param batchSize 更新批次数量 * @return boolean */ boolean updateBatchById(List<T> entityList, int batchSize);

/** * <p> * 根据ID 批量更新全部字段 * </p> * * @param entityList 实体对象列表 * @return boolean */ boolean updateAllColumnBatchById(List<T> entityList);

/** * <p> * 根据ID 批量更新全部字段 * </p> * * @param entityList 实体对象列表 * @param batchSize 更新批次数量 * @return boolean */ boolean updateAllColumnBatchById(List<T> entityList, int batchSize);

/** * <p> * TableId 注解存在更新记录,否插入一条记录 * </p> * * @param entity 实体对象 * @return boolean */ boolean insertOrUpdate(T entity);

/** * 插入或修改一条记录的全部字段 * * @param entity 实体对象 * @return boolean */ boolean insertOrUpdateAllColumn(T entity);

/** * <p> * 根据 ID 查询 * </p> * * @param id 主键ID * @return T */ T selectById(Serializable id);

/** * <p> * 查询(根据ID 批量查询) * </p> * * @param idList 主键ID列表 * @return List<T> */ List<T> selectBatchIds(Collection<? extends Serializable> idList);

/** * <p> * 查询(根据 columnMap 条件) * </p> * * @param columnMap 表字段 map 对象 * @return List<T> */ List<T> selectByMap(Map<String, Object> columnMap);

/** * <p> * 根据 Wrapper,查询一条记录 * </p> * * @param wrapper 实体对象 * @return T */ T selectOne(Wrapper<T> wrapper);

/** * <p> * 根据 Wrapper,查询一条记录 * </p> * * @param wrapper {@link Wrapper} * @return Map<String,Object> */ Map<String, Object> selectMap(Wrapper<T> wrapper);

/** * <p> * 根据 Wrapper,查询一条记录 * </p> * * @param wrapper {@link Wrapper} * @return Object */ Object selectObj(Wrapper<T> wrapper);

/** * <p> * 根据 Wrapper 条件,查询总记录数 * </p> * * @param wrapper 实体对象 * @return int */ int selectCount(Wrapper<T> wrapper);

/** * <p> * 查询列表 * </p> * * @param wrapper 实体包装类 {@link Wrapper} * @return */ List<T> selectList(Wrapper<T> wrapper);

/** * <p> * 翻页查询 * </p> * * @param page 翻页对象 * @return */ Page<T> selectPage(Page<T> page);

/** * <p> * 查询列表 * </p> * * @param wrapper {@link Wrapper} * @return */ List<Map<String, Object>> selectMaps(Wrapper<T> wrapper);

/** * <p> * 根据 Wrapper 条件,查询全部记录 * </p> * * @param wrapper 实体对象封装操作类(可以为 null) * @return List<Object> */ List<Object> selectObjs(Wrapper<T> wrapper);

/** * <p> * 翻页查询 * </p> * * @param page 翻页对象 * @param wrapper {@link Wrapper} * @return */ @SuppressWarnings("rawtypes") Page<Map<String, Object>> selectMapsPage(Page page, Wrapper<T> wrapper);

/** * <p> * 翻页查询 * </p> * * @param page 翻页对象 * @param wrapper 实体包装类 {@link Wrapper} * @return */ Page<T> selectPage(Page<T> page, Wrapper<T> wrapper);

} CoachServiceImpl.java

package com.example.demo.service.impl;

import com.example.demo.model.Coach; import com.example.demo.mapper.CoachMapper; import com.example.demo.service.ICoachService; import com.baomidou.mybatisplus.service.impl.ServiceImpl; import org.springframework.stereotype.Service;

/** * <p> * 教练表 服务实现类 * </p> * * @author the_sardine * @since 2019-04-08 */ @Service public class CoachServiceImpl extends ServiceImpl<CoachMapper, Coach> implements ICoachService {

} mybatisplus封装方法在Servicelmpl中

package com.baomidou.mybatisplus.service.impl;

import java.io.Serializable; import java.util.Collection; import java.util.List; import java.util.Map;

import org.apache.ibatis.binding.MapperMethod; import org.apache.ibatis.session.SqlSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.entity.TableInfo; import com.baomidou.mybatisplus.enums.SqlMethod; import com.baomidou.mybatisplus.exceptions.MybatisPlusException; import com.baomidou.mybatisplus.mapper.BaseMapper; import com.baomidou.mybatisplus.mapper.Condition; import com.baomidou.mybatisplus.mapper.SqlHelper; import com.baomidou.mybatisplus.mapper.Wrapper; import com.baomidou.mybatisplus.plugins.Page; import com.baomidou.mybatisplus.service.IService; import com.baomidou.mybatisplus.toolkit.CollectionUtils; import com.baomidou.mybatisplus.toolkit.MapUtils; import com.baomidou.mybatisplus.toolkit.ReflectionKit; import com.baomidou.mybatisplus.toolkit.StringUtils; import com.baomidou.mybatisplus.toolkit.TableInfoHelper;

/** * <p> * IService 实现类( 泛型:M 是 mapper 对象,T 是实体 , PK 是主键泛型 ) * </p> * * @author hubin * @Date 2016-04-20 */ public class ServiceImpl<M extends BaseMapper<T>, T> implements IService<T> {

@Autowired protected M baseMapper;

/** * <p> * 判断数据库操作是否成功 * </p> * <p> * 注意!! 该方法为 Integer 判断,不可传入 int 基本类型 * </p> * * @param result 数据库操作返回影响条数 * @return boolean */ protected static boolean retBool(Integer result) { return SqlHelper.retBool(result); }

@SuppressWarnings("unchecked") protected Class<T> currentModelClass() { return ReflectionKit.getSuperClassGenricType(getClass(), 1); }

/** * <p> * 批量操作 SqlSession * </p> */ protected SqlSession sqlSessionBatch() { return SqlHelper.sqlSessionBatch(currentModelClass()); }

/** * 获取SqlStatement * * @param sqlMethod * @return */ protected String sqlStatement(SqlMethod sqlMethod) { return SqlHelper.table(currentModelClass()).getSqlStatement(sqlMethod.getMethod()); }

@Transactional(rollbackFor = Exception.class) @Override public boolean insert(T entity) { return retBool(baseMapper.insert(entity)); }

@Transactional(rollbackFor = Exception.class) @Override public boolean insertAllColumn(T entity) { return retBool(baseMapper.insertAllColumn(entity)); }

@Transactional(rollbackFor = Exception.class) @Override public boolean insertBatch(List<T> entityList) { return insertBatch(entityList, 30); }

/** * 批量插入 * * @param entityList * @param batchSize * @return */ @Transactional(rollbackFor = Exception.class) @Override public boolean insertBatch(List<T> entityList, int batchSize) { if (CollectionUtils.isEmpty(entityList)) { throw new IllegalArgumentException("Error: entityList must not be empty"); } try (SqlSession batchSqlSession = sqlSessionBatch()) { int size = entityList.size(); String sqlStatement = sqlStatement(SqlMethod.INSERT_ONE); for (int i = 0; i < size; i++) { batchSqlSession.insert(sqlStatement, entityList.get(i)); if (i >= 1 && i % batchSize == 0) { batchSqlSession.flushStatements(); } } batchSqlSession.flushStatements(); } catch (Throwable e) { throw new MybatisPlusException("Error: Cannot execute insertBatch Method. Cause", e); } return true; }

/** * <p> * TableId 注解存在更新记录,否插入一条记录 * </p> * * @param entity 实体对象 * @return boolean */ @Transactional(rollbackFor = Exception.class) @Override public boolean insertOrUpdate(T entity) { if (null != entity) { Class<?> cls = entity.getClass(); TableInfo tableInfo = TableInfoHelper.getTableInfo(cls); if (null != tableInfo && StringUtils.isNotEmpty(tableInfo.getKeyProperty())) { Object idVal = ReflectionKit.getMethodValue(cls, entity, tableInfo.getKeyProperty()); if (StringUtils.checkValNull(idVal)) { return insert(entity); } else { /* * 更新成功直接返回,失败执行插入逻辑 */ return updateById(entity) || insert(entity); } } else { throw new MybatisPlusException("Error: Can not execute. Could not find @TableId."); } } return false; }

@Transactional(rollbackFor = Exception.class) @Override public boolean insertOrUpdateAllColumn(T entity) { if (null != entity) { Class<?> cls = entity.getClass(); TableInfo tableInfo = TableInfoHelper.getTableInfo(cls); if (null != tableInfo && StringUtils.isNotEmpty(tableInfo.getKeyProperty())) { Object idVal = ReflectionKit.getMethodValue(cls, entity, tableInfo.getKeyProperty()); if (StringUtils.checkValNull(idVal)) { return insertAllColumn(entity); } else { /* * 更新成功直接返回,失败执行插入逻辑 */ return updateAllColumnById(entity) || insertAllColumn(entity); } } else { throw new MybatisPlusException("Error: Can not execute. Could not find @TableId."); } } return false; }

@Transactional(rollbackFor = Exception.class) @Override public boolean insertOrUpdateBatch(List<T> entityList) { return insertOrUpdateBatch(entityList, 30); }

@Transactional(rollbackFor = Exception.class) @Override public boolean insertOrUpdateBatch(List<T> entityList, int batchSize) { return insertOrUpdateBatch(entityList, batchSize, true); }

@Transactional(rollbackFor = Exception.class) @Override public boolean insertOrUpdateAllColumnBatch(List<T> entityList) { return insertOrUpdateBatch(entityList, 30, false); }

@Transactional(rollbackFor = Exception.class) @Override public boolean insertOrUpdateAllColumnBatch(List<T> entityList, int batchSize) { return insertOrUpdateBatch(entityList, batchSize, false); }

/** * 批量插入修改 * * @param entityList 实体对象列表 * @param batchSize 批量刷新个数 * @param selective 是否滤掉空字段 * @return boolean */ private boolean insertOrUpdateBatch(List<T> entityList, int batchSize, boolean selective) { if (CollectionUtils.isEmpty(entityList)) { throw new IllegalArgumentException("Error: entityList must not be empty"); } try (SqlSession batchSqlSession = sqlSessionBatch()) { int size = entityList.size(); for (int i = 0; i < size; i++) { if (selective) { insertOrUpdate(entityList.get(i)); } else { insertOrUpdateAllColumn(entityList.get(i)); } if (i >= 1 && i % batchSize == 0) { batchSqlSession.flushStatements(); } } batchSqlSession.flushStatements(); } catch (Throwable e) { throw new MybatisPlusException("Error: Cannot execute insertOrUpdateBatch Method. Cause", e); } return true; }

@Transactional(rollbackFor = Exception.class) @Override public boolean deleteById(Serializable id) { return SqlHelper.delBool(baseMapper.deleteById(id)); }

@Transactional(rollbackFor = Exception.class) @Override public boolean deleteByMap(Map<String, Object> columnMap) { if (MapUtils.isEmpty(columnMap)) { throw new MybatisPlusException("deleteByMap columnMap is empty."); } return SqlHelper.delBool(baseMapper.deleteByMap(columnMap)); }

@Transactional(rollbackFor = Exception.class) @Override public boolean delete(Wrapper<T> wrapper) { return SqlHelper.delBool(baseMapper.delete(wrapper)); }

@Transactional(rollbackFor = Exception.class) @Override public boolean deleteBatchIds(Collection<? extends Serializable> idList) { return SqlHelper.delBool(baseMapper.deleteBatchIds(idList)); }

@Transactional(rollbackFor = Exception.class) @Override public boolean updateById(T entity) { return retBool(baseMapper.updateById(entity)); }

@Transactional(rollbackFor = Exception.class) @Override public boolean updateAllColumnById(T entity) { return retBool(baseMapper.updateAllColumnById(entity)); }

@Transactional(rollbackFor = Exception.class) @Override public boolean update(T entity, Wrapper<T> wrapper) { return retBool(baseMapper.update(entity, wrapper)); }

@Transactional(rollbackFor = Exception.class) @Override public boolean updateBatchById(List<T> entityList) { return updateBatchById(entityList, 30); }

@Transactional(rollbackFor = Exception.class) @Override public boolean updateBatchById(List<T> entityList, int batchSize) { return updateBatchById(entityList, batchSize, true); }

@Transactional(rollbackFor = Exception.class) @Override public boolean updateAllColumnBatchById(List<T> entityList) { return updateAllColumnBatchById(entityList, 30); }

@Transactional(rollbackFor = Exception.class) @Override public boolean updateAllColumnBatchById(List<T> entityList, int batchSize) { return updateBatchById(entityList, batchSize, false); }

/** * 根据主键ID进行批量修改 * * @param entityList 实体对象列表 * @param batchSize 批量刷新个数 * @param selective 是否滤掉空字段 * @return boolean */ private boolean updateBatchById(List<T> entityList, int batchSize, boolean selective) { if (CollectionUtils.isEmpty(entityList)) { throw new IllegalArgumentException("Error: entityList must not be empty"); } try (SqlSession batchSqlSession = sqlSessionBatch()) { int size = entityList.size(); SqlMethod sqlMethod = selective ? SqlMethod.UPDATE_BY_ID : SqlMethod.UPDATE_ALL_COLUMN_BY_ID; String sqlStatement = sqlStatement(sqlMethod); for (int i = 0; i < size; i++) { MapperMethod.ParamMap<T> param = new MapperMethod.ParamMap<>(); param.put("et", entityList.get(i)); batchSqlSession.update(sqlStatement, param); if (i >= 1 && i % batchSize == 0) { batchSqlSession.flushStatements(); } } batchSqlSession.flushStatements(); } catch (Throwable e) { throw new MybatisPlusException("Error: Cannot execute updateBatchById Method. Cause", e); } return true; }

@Override public T selectById(Serializable id) { return baseMapper.selectById(id); }

@Override public List<T> selectBatchIds(Collection<? extends Serializable> idList) { return baseMapper.selectBatchIds(idList); }

@Override public List<T> selectByMap(Map<String, Object> columnMap) { return baseMapper.selectByMap(columnMap); }

@Override public T selectOne(Wrapper<T> wrapper) { return SqlHelper.getObject(baseMapper.selectList(wrapper)); }

@Override public Map<String, Object> selectMap(Wrapper<T> wrapper) { return SqlHelper.getObject(baseMapper.selectMaps(wrapper)); }

@Override public Object selectObj(Wrapper<T> wrapper) { return SqlHelper.getObject(baseMapper.selectObjs(wrapper)); }

@Override public int selectCount(Wrapper<T> wrapper) { return SqlHelper.retCount(baseMapper.selectCount(wrapper)); }

@Override public List<T> selectList(Wrapper<T> wrapper) { return baseMapper.selectList(wrapper); }

@Override public Page<T> selectPage(Page<T> page) { return selectPage(page, Condition.EMPTY); }

@Override public List<Map<String, Object>> selectMaps(Wrapper<T> wrapper) { return baseMapper.selectMaps(wrapper); }

@Override public List<Object> selectObjs(Wrapper<T> wrapper) { return baseMapper.selectObjs(wrapper); }

@Override public Page<Map<String, Object>> selectMapsPage(Page page, Wrapper<T> wrapper) { wrapper = (Wrapper<T>) SqlHelper.fillWrapper(page, wrapper); page.setRecords(baseMapper.selectMapsPage(page, wrapper)); return page; }

@Override public Page<T> selectPage(Page<T> page, Wrapper<T> wrapper) { wrapper = (Wrapper<T>) SqlHelper.fillWrapper(page, wrapper); page.setRecords(baseMapper.selectPage(page, wrapper)); return page; } }

CoachController.java

package com.example.demo.controller;

import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.plugins.Page; import com.example.demo.model.Coach; import com.example.demo.service.ICoachService;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

/** * <p> * 教练表 前端控制器 * </p> * * @author the_sardine * @since 2019-04-08 */ @RestController @RequestMapping("/coach") public class CoachController { @Autowired private ICoachService iCoachService; @GetMapping("/select")//等同于@RequestMapping(value = "/list",method = RequestMethod.GET) public List<Coach> select(){ return iCoachService.selectList(null); } @RequestMapping("/list") public Page<Coach> list(){ System.out.println("fff"); Page<Coach>selectPage=iCoachService.selectPage(new Page<>(0,10),null); System.out.println("ccc"); System.out.println(selectPage); System.out.println(selectPage.getTotal()); System.out.println(selectPage.getSize()); System.out.println(selectPage.toString()); return selectPage; } @GetMapping("/selects") public String selects(){ return "hello world"; }

} 通过mybatisplus生成的CoachMapper.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.example.demo.mapper.CoachMapper">

<!-- 通用查询映射结果 --> <resultMap id="BaseResultMap" type="com.example.demo.model.Coach"> <id column="id" property="id" /> <result column="lang" property="lang" /> <result column="state" property="state" /> <result column="name" property="name" /> <result column="url" property="url" /> <result column="levelText" property="levelText" /> <result column="levelCode" property="levelCode" /> <result column="coachCode" property="coachCode" /> <result column="context" property="context" /> <result column="sex" property="sex" /> <result column="birth" property="birth" /> <result column="teachAge" property="teachAge" /> <result column="skiAge" property="skiAge" /> <result column="idNumber" property="idNumber" /> <result column="phoneNumber" property="phoneNumber" /> <result column="email" property="email" /> <result column="enableSingleSki" property="enableSingleSki" /> <result column="enableDoubleSki" property="enableDoubleSki" /> <result column="peopleNum" property="peopleNum" /> <result column="introduction" property="introduction" /> <result column="money" property="money" /> <result column="training" property="training" /> <result column="trainingTime" property="trainingTime" /> <result column="area" property="area" /> <result column="createTime" property="createTime" /> <result column="createUserId" property="createUserId" /> <result column="lastModifyTime" property="lastModifyTime" /> <result column="lastModifyUserId" property="lastModifyUserId" /> </resultMap>

</mapper>

入口启动类

package com.example.demo;

import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication @MapperScan("com.example.demo.mapper") public class SpringbootMybatisPlusApplication {

public static void main(String[] args) { SpringApplication.run(SpringbootMybatisPlusApplication.class, args); }

} 运行

在浏览器中输入url地址

控制台打印分页信息

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

扫码关注云+社区

领取腾讯云代金券