SpringBoot整合MybatisPlus并實(shí)現(xiàn)分頁查詢

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

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


<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配置文件如下:具體參數(shù)自己配置

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

代碼生成器部分代碼楣责,不完善


    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) // 設(shè)置生成的service接口名
                /* 首字母是否為I */
                .setIdType(IdType.AUTO); // 主鍵策略//數(shù)據(jù)源配置
        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) // 數(shù)據(jù)庫表映射到實(shí)體的命名策略
                .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();
    }

重點(diǎn):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數(shù)據(jù)庫的方言
        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的分頁慈鸠,強(qiáng)大,簡潔


image

@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 = "根據(jù)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;
    }

看下結(jié)果:


image
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末灌具,一起剝皮案震驚了整個濱河市青团,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌咖楣,老刑警劉巖督笆,帶你破解...
    沈念sama閱讀 222,590評論 6 517
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異诱贿,居然都是意外死亡娃肿,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 95,157評論 3 399
  • 文/潘曉璐 我一進(jìn)店門珠十,熙熙樓的掌柜王于貴愁眉苦臉地迎上來料扰,“玉大人,你說我怎么就攤上這事焙蹭∩硅荆” “怎么了?”我有些...
    開封第一講書人閱讀 169,301評論 0 362
  • 文/不壞的土叔 我叫張陵孔厉,是天一觀的道長拯钻。 經(jīng)常有香客問我帖努,道長,這世上最難降的妖魔是什么粪般? 我笑而不...
    開封第一講書人閱讀 60,078評論 1 300
  • 正文 為了忘掉前任拼余,我火速辦了婚禮,結(jié)果婚禮上亩歹,老公的妹妹穿的比我還像新娘匙监。我一直安慰自己,他們只是感情好捆憎,可當(dāng)我...
    茶點(diǎn)故事閱讀 69,082評論 6 398
  • 文/花漫 我一把揭開白布舅柜。 她就那樣靜靜地躺著,像睡著了一般躲惰。 火紅的嫁衣襯著肌膚如雪致份。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 52,682評論 1 312
  • 那天础拨,我揣著相機(jī)與錄音氮块,去河邊找鬼。 笑死诡宗,一個胖子當(dāng)著我的面吹牛滔蝉,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播塔沃,決...
    沈念sama閱讀 41,155評論 3 422
  • 文/蒼蘭香墨 我猛地睜開眼蝠引,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了蛀柴?” 一聲冷哼從身側(cè)響起螃概,我...
    開封第一講書人閱讀 40,098評論 0 277
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎鸽疾,沒想到半個月后吊洼,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 46,638評論 1 319
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡制肮,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,701評論 3 342
  • 正文 我和宋清朗相戀三年冒窍,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片豺鼻。...
    茶點(diǎn)故事閱讀 40,852評論 1 353
  • 序言:一個原本活蹦亂跳的男人離奇死亡综液,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出儒飒,到底是詐尸還是另有隱情意乓,我是刑警寧澤,帶...
    沈念sama閱讀 36,520評論 5 351
  • 正文 年R本政府宣布,位于F島的核電站届良,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏圣猎。R本人自食惡果不足惜士葫,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 42,181評論 3 335
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望送悔。 院中可真熱鬧慢显,春花似錦、人聲如沸欠啤。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,674評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽洁段。三九已至应狱,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間祠丝,已是汗流浹背疾呻。 一陣腳步聲響...
    開封第一講書人閱讀 33,788評論 1 274
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留写半,地道東北人岸蜗。 一個月前我還...
    沈念sama閱讀 49,279評論 3 379
  • 正文 我出身青樓,卻偏偏與公主長得像叠蝇,于是被迫代替她去往敵國和親璃岳。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,851評論 2 361

推薦閱讀更多精彩內(nèi)容