1. 程式人生 > >SpringBoot整合MybatisPlus並實現分頁查詢

SpringBoot整合MybatisPlus並實現分頁查詢

首先https://start.spring.io/下載一個springBoot的demo。

 

然後增加pomyila依賴,引入以下pom,除了MybatisPlus其他自己分配

<?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>

	<groupId>com.shiyan.my</groupId>
	<artifactId>my</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>

	<name>demo</name>
	<description>Demo project for Spring Boot</description>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.0.3.RELEASE</version>
		<relativePath /> <!-- lookup parent from repository -->
	</parent>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<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>
		<!-- https://mvnrepository.com/artifact/com.baomidou/mybatis-plus-boot-starter -->
		<dependency>
			<groupId>com.baomidou</groupId>
			<artifactId>mybatis-plus-boot-starter</artifactId>
			<version>3.0.6</version>
		</dependency>
		<!-- freemarker -->
		<dependency>
			<groupId>org.freemarker</groupId>
			<artifactId>freemarker</artifactId>
		</dependency>
		<!-- fastjson -->
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>fastjson</artifactId>
			<version>1.2.15</version>
		</dependency>
		<dependency>
			<groupId>com.github.pagehelper</groupId>
			<artifactId>pagehelper</artifactId>
			<version>4.1.4</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>io.springfox</groupId>
			<artifactId>springfox-swagger2</artifactId>
			<version>2.2.2</version>
		</dependency>
		<dependency>
			<groupId>io.springfox</groupId>
			<artifactId>springfox-swagger-ui</artifactId>
			<version>2.2.2</version>
		</dependency>
	</dependencies>

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


</project>

application.properties配置檔案如下:具體引數自己配置

server.port=8080
server.servlet.context-path=/sys
#mysql
spring.datasource.url=jdbc:mysql://localhost:3306/user?useUnicode=true&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

mybatis-plus.mapper-locations=classpath:/mapper/*.xml
mybatis-plus.type-aliases-package=com.shiyan.demo.beans

mybatis-plus.global-config.id-type=0
mybatis-plus.global-config.db-column-underline=true
mybatis-plus.global-config.capital-mode=true

logging.level.com.shiyan.demo.mapper=debug

    

程式碼生成器部分程式碼,不完善

@Test
	public void testGenerator() {
		// 全域性配置
		GlobalConfig config = new GlobalConfig();
		config.setActiveRecord(true) // 是否支援AR模式
				.setAuthor("ais") // 作者
				.setOutputDir("E:\\xuexi\\demo\\src\\main\\java")
				// 生成路徑
				.setFileOverride(true)// 檔案覆蓋
				.setServiceName("%sService").setBaseColumnList(true).setBaseResultMap(true) // 設定生成的service介面名
				/* 首字母是否為I */
				.setIdType(IdType.AUTO); // 主鍵策略//資料來源配置
		DataSourceConfig dsConfig = new DataSourceConfig();
		dsConfig.setDbType(DbType.MYSQL).setUrl("jdbc:mysql://localhost:3306/user")
				.setDriverName("com.mysql.jdbc.Driver").setUsername("root").setPassword("root");
		// 策略配置
		StrategyConfig stConfig = new StrategyConfig();
		stConfig.setCapitalMode(true) // 全域性大寫命名
				//.setDbColumnUnderline(true) // 表名 欄位名 是否使用下滑線命名
				.setNaming(NamingStrategy.underline_to_camel) // 資料庫表對映到實體的命名策略
				.setInclude("tbl_employee") // 生成的表
				.setTablePrefix("tbl_"); // 表字首
		// 包名策略
		PackageConfig pkConfig = new PackageConfig();
		pkConfig.setParent("com.shiyan.demo").setController("controller").setEntity("beans").setService("service");
		AutoGenerator ag = new AutoGenerator().setGlobalConfig(config).setDataSource(dsConfig).setStrategy(stConfig)
				.setPackageInfo(pkConfig);
		ag.execute();
	}

重點:MybatisPlusConfig的配置主要是載入一些外掛注入bean

@Configuration
@EnableTransactionManagement
@MapperScan("com.shiyan.demo.mapper*") 
//掃描dao或者是Mapper介面
public class MybatisPlusConfig {
	
	
	@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;
	}
	
	//配置mybatis的分頁外掛pageHelper
    @Bean
    public PageHelper pageHelper(){
        PageHelper pageHelper = new PageHelper();
        Properties properties = new Properties();
        properties.setProperty("offsetAsPageNum","true");
        properties.setProperty("rowBoundsWithCount","true");
        properties.setProperty("reasonable","true");
        properties.setProperty("dialect","mysql");    //配置mysql資料庫的方言
        pageHelper.setProperties(properties);
        return pageHelper;
    }
}

SwaggerConfig的配置檔案如下

@Configuration
@EnableSwagger2
public class SwaggerConfig {

	@Bean
	public Docket createRestApi() throws IOException {
		return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).select().apis(RequestHandlerSelectors.basePackage("com.shiyan.demo")).paths(PathSelectors.any()).build();
	}

	private ApiInfo apiInfo() throws IOException {
		return new ApiInfoBuilder().title("誓言--------").termsOfServiceUrl("http://data.***.com/").contact("***").version("0.0.1").build();
	}
}

EmployeeController  分頁的有兩個,一個是MybatisPlus自己封裝的一個是PageHelper。

MybatisPlus分頁外掛:單表操作可以用selectPage,下面是測試程式碼,個人推薦用MybatisPlus的分頁,強大,簡潔

@Api("測試")
@RestController
public class EmployeeController {

	@Resource
	private EmployeeService employeeService;

	@ApiOperation(value = "獲取所有使用者")
	@PostMapping("/queryAll")
	public List<Employee> queryEmployees() {
		List<Employee> selectList = employeeService.list();

		return selectList;
	}

	@ApiOperation(value = "新增使用者")
	@PostMapping("/insert")
	public Integer insert(@RequestBody Employee employee) {
		Employee employee2 = new Employee();
		employee2.setAge(employee.getAge());
		employee2.setGender(employee.getGender());
		employee2.setLastName(employee.getLastName());
		employee2.setEmail(employee.getEmail());
		employeeService.save(employee2);
		return employee2.getId();
	}

	@ApiOperation(value = "修改使用者")
	@PostMapping("/update")
	public boolean update(@RequestBody Employee employee) {
		Employee employee2 = new Employee();
		employee2.setAge(employee.getAge());
		employee2.setGender(employee.getGender());
		employee2.setLastName(employee.getLastName());
		employee2.setEmail(employee.getEmail());
		employee2.setId(employee.getId());
		boolean update = employeeService.update(employee2, null);
		return update;
	}

	@ApiOperation(value = "刪除使用者")
	@PostMapping("/delete")
	public boolean delete(@RequestBody Integer id) {

		boolean update = employeeService.removeById(id);
		return update;
	}

	@ApiOperation(value = "根據ID獲取使用者")
	@PostMapping("/getByid")
	public Employee getByid(@RequestBody Integer id) {

		Employee byid = employeeService.getByid(id);
		return byid;
	}

	@ApiOperation(value = "所有")
	@PostMapping("/getAll")
	public IPage<Employee> getAllssss(@RequestBody PageInput input) {

		Page<Employee> page = new Page<>(input.getPageNum(), input.getPageSize());
		IPage<Employee> all = employeeService.getAll(page);
		return all;
	}

	@ApiOperation(value = "所有2")
	@PostMapping("/getAll2")
	public List<Employee> getAllssss2(@RequestBody PageInput input) {

		PageHelper.startPage(input.getPageNum(), input.getPageSize());
		List<Employee> all = employeeService.getAll2();
		Long all2 = employeeService.getAll();
		PageBean<Employee> pageData = new PageBean<>(input.getPageNum(), input.getPageSize(), all2.intValue());
		pageData.setItems(all);
		List<Employee> items = pageData.getItems();
		return items;
	}

看下結果:

 

菜鳥分享===============================PS:Ais永恆