1. 程式人生 > >Springboot整合mybatisPlus實現分頁

Springboot整合mybatisPlus實現分頁

ger control gap for lob spa inf core injection

package lsi.util;

import com.baomidou.mybatisplus.generator.AutoGenerator;
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 com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;

/**
* <p>
* 代碼生成器演示
* </p>
*/
public class MpGenerator {

public static void main(String[] args) {
// assert (false) : "代碼生成屬於危險操作,請確定配置後取消斷言執行代碼生成!";
AutoGenerator mpg = new AutoGenerator();
// 選擇 freemarker 引擎,默認 Velocity
mpg.setTemplateEngine(new FreemarkerTemplateEngine());

// 全局配置
GlobalConfig gc = new GlobalConfig();
gc.setAuthor("LJH");
gc.setOutputDir("F://project/colby/src/main/java");
gc.setFileOverride(false);// 是否覆蓋同名文件,默認是false
gc.setActiveRecord(true);// 不需要ActiveRecord特性的請改為false
gc.setEnableCache(false);// XML 二級緩存
gc.setBaseResultMap(true);// XML ResultMap
gc.setBaseColumnList(false);// XML columList
/* 自定義文件命名,註意 %s 會自動填充表實體屬性! */
// gc.setMapperName("%sDao");
// gc.setXmlName("%sDao");
// gc.setServiceName("MP%sService");
// gc.setServiceImplName("%sServiceDiy");
// gc.setControllerName("%sAction");
mpg.setGlobalConfig(gc);

// 數據源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setDbType(DbType.MYSQL);
dsc.setTypeConvert(new MySqlTypeConvert() {
// 自定義數據庫表字段類型轉換【可選】
@Override
public DbColumnType processTypeConvert(String fieldType) {
System.out.println("轉換類型:" + fieldType);
// 註意!!processTypeConvert 存在默認類型轉換,如果不是你要的效果請自定義返回、非如下直接返回。
return super.processTypeConvert(fieldType);
}
});
dsc.setDriverName("com.mysql.cj.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("123456");
dsc.setUrl("jdbc:mysql://ip:3306/colbyDB?useUnicode=true&characterEncoding=utf8");
mpg.setDataSource(dsc);

// 策略配置
StrategyConfig strategy = new StrategyConfig();
// strategy.setCapitalMode(true);// 全局大寫命名 ORACLE 註意
//strategy.setTablePrefix(new String[]{"user_"});// 此處可以修改為您的表前綴
strategy.setNaming(NamingStrategy.nochange);// 表名生成策略
strategy.setInclude(new String[]{"user"}); // 需要生成的表
// strategy.setExclude(new String[]{"test"}); // 排除生成的表
// 自定義實體父類
// strategy.setSuperEntityClass("com.baomidou.demo.TestEntity");
// 自定義實體,公共字段
// strategy.setSuperEntityColumns(new String[] { "test_id", "age" });
// 自定義 mapper 父類
// strategy.setSuperMapperClass("com.baomidou.demo.TestMapper");
// 自定義 service 父類
// strategy.setSuperServiceClass("com.baomidou.demo.TestService");
// 自定義 service 實現類父類
// strategy.setSuperServiceImplClass("com.baomidou.demo.TestServiceImpl");
// 自定義 controller 父類
// strategy.setSuperControllerClass("com.baomidou.demo.TestController");
// 【實體】是否生成字段常量(默認 false)
// public static final String ID = "test_id";
// strategy.setEntityColumnConstant(true);
// 【實體】是否為構建者模型(默認 false)
// public User setName(String name) {this.name = name; return this;}
// strategy.setEntityBuilderModel(true);
mpg.setStrategy(strategy);

// 包配置
PackageConfig pc = new PackageConfig();
pc.setParent("com.mht.springbootmybatisplus");
// pc.setModuleName("test");
mpg.setPackageInfo(pc);

// 註入自定義配置,可以在 VM 中使用 cfg.abc 【可無】
// InjectionConfig cfg = new InjectionConfig() {
// @Override
// public void initMap() {
// Map<String, Object> map = new HashMap<String, Object>();
// map.put("abc", this.getConfig().getGlobalConfig().getAuthor() +
// "-mp");
// this.setMap(map);
// }
// };
//
// // 自定義 xxList.jsp 生成
// List<FileOutConfig> focList = new ArrayList<>();
// focList.add(new FileOutConfig("/template/list.jsp.vm") {
// @Override
// public String outputFile(TableInfo tableInfo) {
// // 自定義輸入文件名稱
// return "D://my_" + tableInfo.getEntityName() + ".jsp";
// }
// });
// cfg.setFileOutConfigList(focList);
// mpg.setCfg(cfg);
//
// // 調整 xml 生成目錄演示
// focList.add(new FileOutConfig("/templates/mapper.xml.vm") {
// @Override
// public String outputFile(TableInfo tableInfo) {
// return "/develop/code/xml/" + tableInfo.getEntityName() + ".xml";
// }
// });
// cfg.setFileOutConfigList(focList);
// mpg.setCfg(cfg);
//
// // 關閉默認 xml 生成,調整生成 至 根目錄
// TemplateConfig tc = new TemplateConfig();
// tc.setXml(null);
// mpg.setTemplate(tc);

// 自定義模板配置,可以 copy 源碼 mybatis-plus/src/main/resources/templates 下面內容修改,
// 放置自己項目的 src/main/resources/templates 目錄下, 默認名稱一下可以不配置,也可以自定義模板名稱
// TemplateConfig tc = new TemplateConfig();
// tc.setController("...");
// tc.setEntity("...");
// tc.setMapper("...");
// tc.setXml("...");
// tc.setService("...");
// tc.setServiceImpl("...");
// 如上任何一個模塊如果設置 空 OR Null 將不生成該模塊。
// mpg.setTemplate(tc);

// 執行生成
mpg.execute();

// 打印註入設置【可無】
// System.err.println(mpg.getCfg().getMap().get("abc"));
}
}
---------------------------反向生成工具類---------------------------
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE xml>
<configuration scan="true" scanPeriod="60 seconds" debug="false">
<contextName>colby</contextName>
<property name="log.path" value="log" />
<property name="log.maxHistory" value="15" />
<property name="log.pattern" value="%d{HH:mm:ss.SSS} %contextName [%thread] %-5level %logger{36} - %msg%n" />

<!--輸出到控制臺-->
<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>${log.pattern}</pattern>
</encoder>
</appender>

<!--輸出到文件-->
<appender name="file_info" class="ch.qos.logback.core.rolling.RollingFileAppender">
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${log.path}/info/info.%d{yyyy-MM-dd}.log</fileNamePattern>
<MaxHistory>${log.maxHistory}</MaxHistory>
</rollingPolicy>
<encoder>
<pattern>${log.pattern}</pattern>
</encoder>
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>INFO</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
</appender>

<appender name="file_error" class="ch.qos.logback.core.rolling.RollingFileAppender">
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${log.path}/error/error.%d{yyyy-MM-dd}.log</fileNamePattern>
</rollingPolicy>
<encoder>
<pattern>${log.pattern}</pattern>
</encoder>
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>ERROR</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
</appender>

<root level="debug">
<appender-ref ref="console" />
</root>

<root level="info">
<appender-ref ref="file_info" />
<appender-ref ref="file_error" />
</root>
</configuration>
-------------------logback-spring.xml-----------------------
# 配置slq打印日誌
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
-------------------------------------------------------
@SpringBootApplication
@NacosPropertySource(dataId = "springboot2-nacos-config", autoRefreshed = true)
public class ColbyApplication {

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

@Bean
public PaginationInterceptor paginationInterceptor() {
PaginationInterceptor page = new PaginationInterceptor();
page.setDialectType("mysql");

return page;
}

@Bean
public PerformanceInterceptor performanceInterceptor() {
PerformanceInterceptor page = new PerformanceInterceptor();
page.setFormat(true);
return page;
}

}
-------------------需要添加-----------------------
@RequestMapping("/queryCtionUser/{currentPage}")
@ResponseBody
public ResponseBo queryConditionUser(@PathVariable("currentPage")int currentPage) {
Page<User> page = new Page<>(currentPage, 2);//這裏寫死了每頁顯示數量
Page<User> userList = userServiceImpl.selectPage(page, new EntityWrapper<User>()
//.between("age", 18, 50)
.like("name", "jacck")//查詢條件
//.eq("last_name", "tom")
);
System.out.println(userList);
System.out.println("================= 相關的分頁信息 ==================");
System.out.println("總條數:" + userList.getTotal());
System.out.println("當前頁碼:" + userList.getCurrent());
System.out.println("總頁數:" + userList.getPages());
System.out.println("每頁顯示條數:" + userList.getSize());
System.out.println("是否有上一頁:" + userList.hasPrevious());
System.out.println("是否有下一頁:" + userList.hasNext());
//還可以將查詢到的結果set進page對象中
return ResponseBo.ok(userList);
}
-------------------實現代碼----------------------不需要pagehelper.jar跟它無關
http://localhost:9595/user/queryCtionUser/2
技術分享圖片

 

Springboot整合mybatisPlus實現分頁