mybatis ----- baseMapper、pagehelper、generator整合(springboot)
mybatis ----- baseMapper、pagehelper、generator整合(springboot)
加入引用
<!--mybatis start-->
<!--mybatis-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.1</version>
</dependency>
<!--mapper-->
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper-spring-boot-starter</artifactId>
<version>1.3.1</version>
</dependency>
<!--pagehelper-->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.3</version>
</dependency>
<!--mybatis end -->
加入build 插件
org.mybatis.generator
mybatis-generator-maven-plugin
1.3.2
${basedir}/src/main/resources/generator/generatorConfig.xml
true
true
mysql
mysql-connector-java
${mysql.version}
tk.mybatis
mapper
${mapper.version}
>将逆向工程文件放入/src/main/resources/下,如图 ![](https://images2018.cnblogs.com/blog/1235870/201805/1235870-20180517110958251-988363317.png)
config.properties文件
# 数据库配置
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test #数据库名字,账号,密码
jdbc.user=root
jdbc.password=root
#c3p0
jdbc.maxPoolSize=50
jdbc.minPoolSize=10
jdbc.maxStatements=100
jdbc.testConnection=true
# 通用Mapper配置
mapper.plugin=tk.mybatis.mapper.generator.MapperPlugin
mapper.Mapper=com.tzy.test.lib.MyBaseMapper #生成mapper继承哪个mapper(因为tk.mapper有所有常用单表查询),路径对应
>而这个通用mapper一般放在lib下
package com.tzy.test.lib;
import tk.mybatis.mapper.common.Mapper;
import tk.mybatis.mapper.common.MySqlMapper;
public interface MyBaseMapper<T> extends Mapper<T>, MySqlMapper<T> {
}
generatorConfig.xml 用于生成配置
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<properties resource="generator/config.properties"/>
<context id="Mysql" targetRuntime="MyBatis3Simple" defaultModelType="flat">
<property name="javaFileEncoding" value="UTF-8"/>
<property name="beginningDelimiter" value="`"/>
<property name="endingDelimiter" value="`"/>
<plugin type="${mapper.plugin}">
<property name="mappers" value="${mapper.Mapper}"/>
</plugin>
<jdbcConnection driverClass="${jdbc.driverClass}" connectionURL="${jdbc.url}" userId="${jdbc.user}"
password="${jdbc.password}"/>
<!--生成实体类在那个路径下-->
<javaModelGenerator targetPackage="com.tzy.test.biz.model" targetProject="src/main/java"/>
<!--生成的mapper.xml在那个路径下-->
<sqlMapGenerator targetPackage="mapper/biz/" targetProject="src/main/resources"/>
<!--生成实体mapper在那个路径下-->
<javaClientGenerator targetPackage="com.tzy.test.biz.mapper" targetProject="src/main/java" type="XMLMAPPER"/>
<!--那个表需要生成逆向工程,对应的实体类叫什么-->
<table tableName="t_report_enclosure" domainObjectName="ReportEnclosure"/>
</context>
</generatorConfiguration>
>然后通过插件启动就可以了,去自己设定的目录里面找找看吧 ![](https://images2018.cnblogs.com/blog/1235870/201805/1235870-20180517112254983-600322811.png)
对分页工具的封装
首先是Page.java
import java.io.Serializable;
public final class Page implements Serializable {
private int pageNum;
private int pageSize;
public int getPageNum() {
return pageNum;
}
public int getPageSize() {
return pageSize;
}
private Page() {
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + pageNum;
result = prime * result + pageSize;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
Page other = (Page) obj;
if (pageNum != other.pageNum) return false;
if (pageSize != other.pageSize) return false;
return true;
}
@Override
public String toString() {
return "Page [pageNum=" + pageNum + ", pageSize=" + pageSize + "]";
}
public static class PageBuilder {
private PageBuilder() {
}
public static final Page build(String pageNum, String pageSize) {
if (pageNum == null || !pageNum.matches("[1-9]\\d*")) return null;
if (pageSize == null || !pageSize.matches("[1-9]\\d*")) pageSize = "10";
return build(new Integer(pageNum), new Integer(pageSize));
}
public static final Page build(Integer pageNum, Integer pageSize) {
if (pageNum == null || pageNum.intValue() == 0) return null;
if (pageSize == null || pageSize.intValue() < 1) pageSize = 10;
Page page = new Page();
page.pageNum = pageNum.intValue();
page.pageSize = pageSize.intValue();
return page;
}
}
}
>然后是sort.java
import java.io.Serializable;
public final class Sort implements Serializable {
private String orderBy;
public String getOrderBy() {
return orderBy;
}
private Sort() {
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((orderBy == null) ? 0 : orderBy.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
Sort other = (Sort) obj;
if (orderBy == null) {
if (other.orderBy != null) return false;
} else if (!orderBy.equals(other.orderBy)) return false;
return true;
}
@Override
public String toString() {
return "Sort [orderBy=" + orderBy + "]";
}
public static class SortBuilder {
private SortBuilder() {
}
public static final Sort build(String sortBy, String sortType) {
return build(new String[]{sortBy}, new String[]{sortType});
}
public static final Sort build(String[] sortBys, String[] sortTypes) {
if (sortBys == null || sortBys.length == 0 || sortTypes == null || sortTypes.length != sortBys.length)
return null;
StringBuilder builder = new StringBuilder();
for (int i = 0, l = sortBys.length; i < l; i++) {
String sortBy = toUnderline(sortBys[i]);
String sortType = sortTypes[i];
if (sortBy == null || sortBy.trim().length() == 0) return null;
if (sortType == null || !sortType.equalsIgnoreCase("desc")) sortType = "asc";
if (i > 0) builder.append(",");
builder.append(sortBy).append(" ").append(sortType);
}
Sort sort = new Sort();
sort.orderBy = builder.toString();
return sort;
}
/**
* 驼峰转下划线
*
* @param str
* @return
*/
private static final String toUnderline(String str) {
if (str == null) return null;
StringBuilder builder = new StringBuilder();
boolean upperCase = false;
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
boolean nextUpperCase = true;
if (i < str.length() - 1) nextUpperCase = Character.isUpperCase(str.charAt(i + 1));
if (i >= 0 && Character.isUpperCase(c)) {
if (!upperCase || !nextUpperCase) if (i > 0) builder.append("_");
upperCase = true;
} else upperCase = false;
builder.append(Character.toLowerCase(c));
}
return builder.toString();
}
}
}
>其次是
import com.github.pagehelper.PageHelper;
public class PageSortUtil {
/**
* 执行分页和排序
*
* @param page
* @param sort
*/
public static void doPagingAndSorting(Page page, Sort sort) {
if (page != null) PageHelper.startPage(page.getPageNum(), page.getPageSize());
if (sort != null) PageHelper.orderBy(sort.getOrderBy());
}
/**
* 执行分页
*
* @param page
*/
public static void doPaging(Page page) {
doPagingAndSorting(page, null);
}
/**
* 执行分页
*
* @param pageNum
* @param pageSize
*/
public static void doPaging(Integer pageNum, Integer pageSize) {
Page page = Page.PageBuilder.build(pageNum, pageSize);
doPaging(page);
}
/**
* 执行分页
*
* @param pageNum
*/
public static void doPaging(Integer pageNum) {
doPaging(pageNum, null);
}
/**
* 执行排序
*
* @param sort
*/
public static void doSorting(Sort sort) {
doPagingAndSorting(null, sort);
}
/**
* 执行排序
*
* @param sortBys
* @param sortTypes
*/
public static void doSorting(String[] sortBys, String[] sortTypes) {
Sort sort = Sort.SortBuilder.build(sortBys, sortTypes);
doSorting(sort);
}
/**
* 执行排序
*
* @param sortBy
* @param sortType
*/
public static void doSorting(String sortBy, String sortType) {
doSorting(new String[]{sortBy}, new String[]{sortType});
}
/**
* 执行排序
*
* @param sortBy
*/
public static void doSorting(String sortBy) {
doSorting(sortBy, null);
}
}
>在封装一层使调用更加方便吧。
import java.io.Serializable;
/**
* @Created by Heaton on 2018/5/14.
* @describe 分页执行者
*/
public class PojoPageHandler implements Serializable {
/**
* @param
* @return
* @date 2018/5/14 11:31
* @describe 执行分页和排序
*/
public static void doPagingAndSorting(Object obj) {
try {
Class<?> clazz = obj.getClass();
String sort = (String) clazz.getMethod("getSort").invoke(obj);
String order = (String) clazz.getMethod("getOrder").invoke(obj);
Integer pageNum = (Integer) clazz.getMethod("getPageNum").invoke(obj);
Integer pageSize = (Integer) clazz.getMethod("getPageSize").invoke(obj);
Sort sortObj = Sort.SortBuilder.build(sort, order);
Page pageObj = Page.PageBuilder.build(pageNum, pageSize);
PageSortUtil.doPagingAndSorting(pageObj, sortObj);
} catch (Exception e) {
e.printStackTrace();
}
}
}
>好了,怎么调用呢?首先分页流程是,前台将传递4个参数给我们,当前页码,需要显示条数,按什么字段排序,按升序还是降序。 >这里创建一个公用的来接收这几个参数的类,下面用的swagger注解,不喜欢可以去掉。查询条件是用来做模糊查询的(这里可以不管),详情参考--动态mapper写法贴。 >注意,分页设置只对第一次查询的sql语句生效。
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
@ApiModel(description = "公用查询对象")
public class CommonSelectVo {
@ApiModelProperty(value = "页码")
private Integer pageNum;
@ApiModelProperty(value = "每页条数")
private Integer pageSize;
@ApiModelProperty(value = "排序字段")
private String sort;
@ApiModelProperty(value = "排序方式")
private String order;
@ApiModelProperty(value = "查询条件")
private String queryCriteria;
}
>调用方法 ![](https://images2018.cnblogs.com/blog/1235870/201805/1235870-20180517113443828-611564085.png)
然后将查询出来的数据丢给Json.ok处理
import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import com.longe.nuclear.exception.CommonErrorCode;
import com.longe.nuclear.exception.ErrorCode;
import lombok.Data;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Data
public class JsonData<T> {
private final static Integer CODE_SUCCESS = 200;
private final static String msgSuccess = "success";
public final static Integer CODE_FAILURE = -1;
private Integer code;
private String msg;
private T data;
private Long timestamp;
public JsonData(Integer code, String msg, T data) {
this.code = code;
this.msg = msg;
this.data = data;
timestamp = System.currentTimeMillis();
}
public JsonData(Integer code, String msg) {
this.code = code;
this.msg = msg;
timestamp = System.currentTimeMillis();
}
public static <T> JsonData<T> ok(T data) {
return new JsonData<>(CODE_SUCCESS, msgSuccess, data);
}
public static <T> JsonData ok(List<T> data) {
if (data instanceof Page) {
Map<String, Object> map = new HashMap();
List<T> list = new ArrayList<T>();
for (T object : data) {
list.add(object);
}
map.put("list", list);
PageInfo info = new PageInfo(data);
map.put("total", info.getTotal());
map.put("pages", info.getPages());
map.put("size", info.getSize());
map.put("pageSize", info.getPageSize());
map.put("pageNum", info.getPageNum());
return new JsonData(CODE_SUCCESS, msgSuccess, map);
} else {
return new JsonData(CODE_SUCCESS, msgSuccess, data);
}
}
public static JsonData ok() {
return new JsonData(CODE_SUCCESS, msgSuccess);
}
public static JsonData error(ErrorCode errorCode) {
return new JsonData(errorCode.getCode(), errorCode.getErrorMsg());
}
public static JsonData error() {
return error(CommonErrorCode.INNER_ERROR);
}
public static JsonData error(Integer errorCode, String msg) {
return new JsonData(errorCode, msg);
}
}
>我们将集合传递给了json.OK(),然后判断他是否是Page类, ![](https://images2018.cnblogs.com/blog/1235870/201805/1235870-20180517113954187-886741345.png)
您的资助是我最大的动力!
金额随意,欢迎来赏!