本文主要是介绍springboot+mybatis-plus实现三表(两两联立,总共五个表)分页查找,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
一.依赖
<dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-devtools</artifactId><scope>runtime</scope><optional>true</optional></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency><!--Swagger2--><dependency><groupId>io.springfox</groupId><artifactId>springfox-swagger2</artifactId><version>2.9.2</version></dependency><dependency><groupId>io.springfox</groupId><artifactId>springfox-swagger-ui</artifactId><version>2.9.2</version></dependency><!-- 加载mybatis-plus整合springboot --><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.3.2</version></dependency><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus</artifactId><version>3.3.2</version></dependency><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-generator</artifactId><version>3.3.2</version></dependency><!--引入thymeleaf依赖--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-thymeleaf</artifactId></dependency><!-- 模板引擎 代码生成 --><dependency><groupId>org.apache.velocity</groupId><artifactId>velocity-engine-core</artifactId><version>2.2</version></dependency><!-- MySQL的jdbc驱动包 --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.20</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version></dependency><dependency><groupId>org.junit.platform</groupId><artifactId>junit-platform-launcher</artifactId><version>1.6.2</version></dependency><dependency><groupId>log4j</groupId><artifactId>log4j</artifactId><version>1.2.17</version></dependency><!-- 排除自带的日志依赖 --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId><exclusions><exclusion><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-logging</artifactId></exclusion></exclusions></dependency></dependencies>
二.mybatis-plus自动生成配置文件
package com.lwg.practise.config;import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;import org.springframework.boot.autoconfigure.thymeleaf.ThymeleafTemplateAvailabilityProvider;import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
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.FileOutConfig;
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.TemplateConfig;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import com.baomidou.mybatisplus.generator.engine.VelocityTemplateEngine;public class CodeGenerator {/*** <p>* 读取控制台内容* </p>*/public static String scanner(String tip) {Scanner scanner = new Scanner(System.in);StringBuilder help = new StringBuilder();help.append("请输入" + tip + ":");System.out.println(help.toString());if (scanner.hasNext()) {String ipt = scanner.next();if (StringUtils.isNotEmpty(ipt)) {return ipt;}}throw new MybatisPlusException("请输入正确的" + tip + "!");}public static void main(String[] args) {// 代码生成器AutoGenerator mpg = new AutoGenerator();// 全局配置GlobalConfig gc = new GlobalConfig();String projectPath = System.getProperty("user.dir");gc.setOutputDir(projectPath + "/src/main/java");gc.setAuthor("lwg");gc.setOpen(false);// gc.setSwagger2(true); 实体属性 Swagger2 注解mpg.setGlobalConfig(gc);// 数据源配置DataSourceConfig dsc = new DataSourceConfig();dsc.setUrl("jdbc:mysql://39.96.48.41:3306/task?useUnicode=true&useSSL=false&characterEncoding=utf8");// dsc.setSchemaName("public");dsc.setDriverName("com.mysql.jdbc.Driver");dsc.setUsername("root");dsc.setPassword("109837");mpg.setDataSource(dsc);// 包配置PackageConfig pc = new PackageConfig();pc.setParent("com.lwg.practise");mpg.setPackageInfo(pc);// 自定义配置InjectionConfig cfg = new InjectionConfig() {@Overridepublic void initMap() {// to do nothing}};// 如果模板引擎是 freemarker
// String templatePath = "/templates/mapper.xml.ftl";// 如果模板引擎是 velocityString templatePath = "/templates/mapper.xml.vm";// 自定义输出配置List<FileOutConfig> focList = new ArrayList<>();// 自定义配置会被优先输出focList.add(new FileOutConfig(templatePath) {@Overridepublic String outputFile(TableInfo tableInfo) {// 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!return projectPath + "/src/main/java/com/lwg/practise/mapper/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;}});cfg.setFileOutConfigList(focList);mpg.setCfg(cfg);// 配置模板TemplateConfig templateConfig = new TemplateConfig();templateConfig.setXml(null);mpg.setTemplate(templateConfig);// 策略配置StrategyConfig strategy = new StrategyConfig();strategy.setNaming(NamingStrategy.underline_to_camel);strategy.setColumnNaming(NamingStrategy.underline_to_camel);strategy.setEntityLombokModel(true);strategy.setRestControllerStyle(true);strategy.setInclude(scanner("表名,多个英文逗号分割").split(","));strategy.setControllerMappingHyphenStyle(true);strategy.setTablePrefix(pc.getModuleName() + "_");mpg.setStrategy(strategy);mpg.setTemplateEngine(new VelocityTemplateEngine());mpg.execute();}}
分页配置
package com.lwg.practise.config;import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.plugins.pagination.optimize.JsqlParserCountOptimize;@Configuration
@MapperScan("com.lwg.practise.mapper.*")
public class PageConfig {@Beanpublic PaginationInterceptor paginationInterceptor(){PaginationInterceptor interceptor = new PaginationInterceptor();//设置请求的页面大于最大页面后操作,true调回到首页,false继续请求,默认false//interceptor.setOverflow(false);//设置最大单页限制数量,默认500条,-1不受限制/* interceptor.setLimit(500);*/interceptor.setCountSqlParser(new JsqlParserCountOptimize(true));return interceptor;}
}
swagger配置
package com.lwg.practise.config;import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;@Configuration
@EnableSwagger2
@EnableWebMvc
@ComponentScan(basePackages = "com.lwg.practise.controller")
public class SwaggerConfig implements WebMvcConfigurer {@Beanpublic Docket api() {return new Docket(DocumentationType.SWAGGER_2).select().apis(RequestHandlerSelectors.basePackage("com.lwg.practise.controller")).build().apiInfo(apiInfo());}private ApiInfo apiInfo() {return new ApiInfoBuilder().title("项目接口测试文档").description("项目接口测试").version("1.1").termsOfServiceUrl("").license("").licenseUrl("").build();}@Overridepublic void addResourceHandlers(ResourceHandlerRegistry registry) {registry.addResourceHandler("/**").addResourceLocations("classpath:/static/");registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");WebMvcConfigurer.super.addResourceHandlers(registry);}
}
三.实体类
Grade.java
package com.lwg.practise.entity;import java.io.Serializable;
import java.util.List;import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;/*** <p>* * </p>** @author lwg* @since 2020-08-10*/
@Data
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode(callSuper = false)
public class Grade implements Serializable {private static final long serialVersionUID=1L;private String id;private String name;List<Teacher> teachers;
}
SGrade.java
package com.lwg.practise.entity;import java.io.Serializable;import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;/*** <p>* * </p>** @author lwg* @since 2020-08-10*/
@Data
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode(callSuper = false)
public class SGrade implements Serializable {private static final long serialVersionUID=1L;private String id;/*** 学生id*/private String sId;/*** 年级id*/private String gId;}
Student.java
package com.lwg.practise.entity;import java.io.Serializable;
import lombok.Data;
import lombok.EqualsAndHashCode;/*** <p>* * </p>** @author lwg* @since 2020-08-10*/
@Data
@EqualsAndHashCode(callSuper = false)
public class Student implements Serializable {private static final long serialVersionUID=1L;private String id;/*** 学号*/private String sno;/*** 姓名*/private String name;/*** 年龄*/private String age;/*** 分数*/private Integer score;/*** 电话*/private String phone;private String address;private Teacher teachers;}
Teacher.java
package com.lwg.practise.entity;import java.io.Serializable;
import java.util.List;import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;/*** <p>* * </p>** @author lwg* @since 2020-08-10*/
@Data
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode(callSuper = false)
public class Teacher implements Serializable {private static final long serialVersionUID=1L;private String id;private String name;List<Student> students;private Grade grade;}
STeacher.java
package com.lwg.practise.entity;import java.io.Serializable;import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;/*** <p>* * </p>** @author lwg* @since 2020-08-10*/
@Data
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode(callSuper = false)
public class STeacher implements Serializable {private static final long serialVersionUID=1L;private String id;/*** 学生id*/private String tId;/*** 老师id*/private String sId;}
StudentMapper.java
package com.lwg.practise.mapper;import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Constants;
import com.lwg.practise.entity.Student;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;/*** <p>* Mapper 接口* </p>** @author lwg* @since 2020-08-10*/
@Mapper
public interface StudentMapper extends BaseMapper<Student> {IPage<Student> selectInfoByPage(IPage<Student> page);
}
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.lwg.practise.mapper.StudentMapper"><resultMap id="students" type="com.lwg.practise.entity.Student"><id column="id" property="id"/><result column="sname" property="name"/><association property="teachers" javaType="com.lwg.practise.entity.Teacher"><id column="id" property="id"/><result column="tname" property="name"/><association property="grade" javaType="com.lwg.practise.entity.Grade"><id column="id" property="id"/><result column="gname" property="name"/></association></association></resultMap><select id="selectInfoByPage" resultMap="students">select s.name as sname,t.name as tname,g.name as gnamefrom student sinner join s_teacher st on s.id=st.s_idinner join teacher t on t.id=st.t_idinner join s_grade sg on s.id=sg.s_idinner join grade g on g.id=sg.g_idwhere 1=1</select>
</mapper>
四 测试
package com.lwg.practise;import java.util.List;import org.apache.log4j.Logger;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lwg.practise.entity.Student;
import com.lwg.practise.mapper.StudentMapper;@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
@MapperScan(basePackages = {"com.lwg.practise.mapper"})
class PractiseApplicationTests {static Logger logger = Logger.getLogger(PractiseApplicationTests.class);@Autowiredprivate StudentMapper studentMapper;@Testpublic void selectByPage(){Page<Student> page = new Page<>(0,2);Page<Student> studentPage = (Page<Student>) studentMapper.selectInfoByPage(page);System.out.println("总页数"+studentPage.getPages());System.out.println("总记录数"+studentPage.getTotal());List<Student> records = studentPage.getRecords();records.forEach(System.out::println);}
}
五 测试结果
这篇关于springboot+mybatis-plus实现三表(两两联立,总共五个表)分页查找的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!