Micro projects: take you step by step using SpringBoot Getting Started (b)

Today we use JPA project and do pagination explaining to do

If you are new to a friend Please return a
Previous: micro-projects (a)

maven integration

Pom in the file dependenciesto import the following dependencies dependencies

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

Then restart the project

, we can see that after running out of the project up and running a tomcat

We can see here the emergence of a 404 error. Although this is wrong, but out on the right.

Let's configure the project and increase search

Before doing by check, we need to create two packages.

Let us fill things one by one.

service

It is a logical service layer, including data processing direction, and processes.

The first method is easy to understand here is that the article is added to the database.

The second method is to check the meaning of a database on behalf of paging,

Why do it? Quite simply, if we can not show too much data to do so. ID are arranged in reverse order.

package cn.baldorange.anonymous.service;

import cn.baldorange.anonymous.entity.Wall;
import cn.baldorange.anonymous.repository.WallRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import java.util.Date;

@Service
public class WallService {
    @Autowired
    WallRepo wallRepo;

    /**
     * 增加吐槽
     * @param title
     * @param content
     * @return
     */
    public Boolean saveNewWall(String title,String content){
        try {
            String summary = "";
            if (content.length() > 100)
                summary = content.substring(0, 99);
            else summary = content;
            Wall wall = new Wall(title, content, new Date(), summary, "0");
            wallRepo.save(wall);
            return true;
        }catch (Exception e){
            return false;
        }
    }



    /**
     * 获得匿名墙的所有文章
     * @return
     */
    public Page<Wall> findAllWalls(Integer page,Integer size){
        if(page == null) page = 0;
        if(size == null) size =10;
        PageRequest pageable = PageRequest.of(page, size, Sort.Direction.DESC, "id");
        return wallRepo.findAll(pageable);
    }
}

controller

As Controller layer is relatively simple,

But coming from a servlet students to pay attention, @PutMappingthis will bring you may wonder, in fact, now commonly used not only get http requests and post also put delete, and so we have not seen before, provision is man-made, people can change.

package cn.baldorange.anonymous.controller;

import cn.baldorange.anonymous.entity.Wall;
import cn.baldorange.anonymous.service.WallService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/walls")
public class Controller {
    @Autowired
    WallService wallService;

    @PutMapping("/saveNewWall")
    public Boolean saveNewWall(@RequestParam String title,@RequestParam String content){
        return wallService.saveNewWall(title,content);
    }


    @GetMapping("/findAllWalls")
    public Page<Wall> findAllWalls(Integer page, Integer size){
        return wallService.findAllWalls(page,size);
    }

}

After configuring the access we start here:
http://127.0.0.1:8080/walls/findAllWalls

This is what we have seen json data

Although the mess, but we can easily find that there are content in our database. There are other things.

Here we need to configure the interface files.

swagger

I believe both front-end or back-end development, are more or less been tortured interface documentation. Front-end to back-end interface often complain that the document is inconsistent with the actual situation. I feel the back end interface documentation to write and maintenance will cost a lot of energy, often too late update. In fact, both front-end back-end call, back-end or back-end call, expect to have a good interface documentation. But the interface documentation for programmers, just as comments, often complain that the code written by someone else did not write notes, however, to write their own code for starting up, the most annoying, but also write comments. So just only by forcing everyone to regulate is not enough, over time, an iterative version, interface documentation is often very easy to keep up with the code.

First introduced swagger maven

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

Then we create a final package directory as follows:

swaggerConfig configuration file as follows:

package cn.baldorange.anonymous.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class swaggerConfig {
    @Bean
    Docket docket(){
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any())
                .build()
                .apiInfo(new ApiInfoBuilder().description("项目").build());
    }
}

OK now we restart the project:
and visit here,

OK we can now use the swagger interface tested, fried chicken sticks.

Paging

Database page is written query in the database, except that the query is a specified number of pieces of data to the specified number of pieces, not a one-time check out the full data.

When size = 2, returns the following

when the size = 2, page = 2, returns the following

when the page size or out of range, returns the following

Field Description tab here after as follows:

{
    "content": [{}], // 数据列表
    "last": true, // 是否最后一页
    "totalPages": 1, // 总页数
    "totalElements": 1, // 数据总数
    "sort": null, // 排序
    "first": true, // 是否首页
    "numberOfElements": 1, // 本页数据条数
    "size": 10, // 每页长度
    "number": 0 // 当前页序号
}

Not difficult to see, JPA paging mechanism is particularly useful, just do not be too cool.

git push up

OK today live on the completion.

Guess you like

Origin www.cnblogs.com/godoforange/p/11615740.html