Microprojects: Step by step, take you to the beginning of SpringBoot

Keywords: Java Database Maven Spring Tomcat

Today, let's use JPA to do paging projects and explain them.

If you are a new friend, please return to the last one.
Last article: Microprojects (I)

maven integration

Import the following dependencies into the dependencies dependencies dependencies of the pom file

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

Then restart the project

We can see that the project runs out of a tomcat

We can see 404 errors here. It's a mistake, but it's right to come out.

Now let's configure the addition and check of the project.

We need to build two new packages before we do additional checks.

Now let's fill in one by one.

service

service is the logical layer, including the direction and process of data processing.

The first way to understand this is to add articles to the database.

The second method is to paginate the database.

Why do we do this? Simply, if there is too much data to show, we can only do that. In reverse order of ID.

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;

    /**
     * Add Tucao
     * @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;
        }
    }



    /**
     * Get all the articles on the anonymous wall
     * @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 for the Controller layer, it's simpler.

But the students coming from the servlet should pay attention to that @PutMapping may bring you doubts. In fact, http requests are not only used for get and post, but also for put delete, which we haven't seen before. The rules are fixed and can be changed.

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, we will visit here after booting up:
http://127.0.0.1:8080/walls/findAllWalls

This is the json data we see

Although it's messy, it's not difficult for us to find the contents in our database. There are other things.

Now we need to configure the interface file.

swagger

I believe that both front-end and back-end development have been more or less tortured by interface documents. The front end often complains that the interface documents given by the back end are inconsistent with the actual situation. The back end also feels that it takes a lot of energy to write and maintain interface documents, and it is often too late to update them. In fact, both front-end call back-end and back-end call back-end expect a good interface document. But this interface document for programmers, just like annotations, often complains that the code written by others is not written. However, when writing code, the most annoying thing is to write notes. So it is not enough to regulate people only by coercion. Over time, version iteration, interface documents tend to be too easy to keep up with the code.

First, introduce maven into swagger

        <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 new package with the final directory as follows:

The swaggerConfig configuration file is 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("project").build());
    }
}

OK We are now restarting the project:
And visit Here

OK now we can use swagger for interface testing, fried chicken sticks.

Paging technology

Database paging is also a query statement written in the database, the difference is that the query is the data from the specified number of bars to the specified number of bars, not all the data are checked out at one time.

When size=2, return as follows

When size=2,page=2, return as follows

When size or page crosses the boundary, return as follows

The paginated fields here are described as follows:

{
    "content": [{}], // Data list
    "last": true, // Is it the last page?
    "totalPages": 1, // PageCount
    "totalElements": 1, // Total data
    "sort": null, // sort
    "first": true, // Is it home page?
    "numberOfElements": 1, // Number of data bars on this page
    "size": 10, // Length per page
    "number": 0 // Current page number
}

It's not hard to see that the paging mechanism of JPA is very easy to use. It's not too cool.

git push up

OK's work is finished today.

Posted by mwilson2 on Tue, 08 Oct 2019 11:48:13 -0700