1. Pom. XML dependency

<! Mapper = mapper = mapper
<! -- https://mvnrepository.com/artifact/tk.mybatis/mapper-spring-boot-starter -->
<dependency>
    <groupId>tk.mybatis</groupId>
    <artifactId>mapper-spring-boot-starter</artifactId>
    <version>2.0.2</version>
</dependency>
<! -- JPA dependency packages, each Pojo, need to use the corresponding annotations of the package -->
<dependency>
    <groupId>javax.persistence</groupId>
    <artifactId>persistence-api</artifactId>
    <version>1.0</version>
    <scope>compile</scope>
</dependency>
<! - swagger document -- >
<! -- http://localhost:9011/swagger-ui.html -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.6.1</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.6.1</version>
</dependency>
Copy the code

Mapper does not need to configure mybatis in the application.yaml configuration file.

2. Brand entities

Here I do a Brand object related to add, delete and change!

/ * * *@Auther: csp1999
 * @Date: 2020/12/24/9:26
 * @Description: Brand Entity */
@ApiModel(description = "Brand", value = "Brand")
@Table(name = "tb_brand")
public class Brand implements Serializable {

    /** * brand id */
    @APIModelProperty (value = "brand id", Required = false)
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private Integer id;

    /** * brand name */
    @APIModelProperty (value = "brand name ", Required = false)
    @Column(name = "name")
    private String name;

    /** ** **
    @apiModelProperty (value = "brand image address ", Required = false)
    @Column(name = "image")
    private String image;

    /** * the first letter of the brand */
    @APIModelProperty (value = "brand initial ", Required = false)
    @Column(name = "letter")
    private String letter;

    /** ** sort */
    @APIModelProperty (value = "sort ", Required = false)
    @Column(name = "seq")
    private Integer seq;
    
    /* The setter/getter method omitted */
}
Copy the code

3. Implement universal Mapper interfaces

/ * * *@Auther: csp1999
 * @Date: 2020/12/24 / keep *@Description: Brand related Mapper */
@Repository
public interface BrandMapper extends Mapper<Brand> {}Copy the code

4. The Service interface

* * *@Auther: csp1999
 * @Date: 2020/12/24/17:18
 * @Description: Brand Brand related Service interface */public interface BrandService {

    /** * query all brand information **@return* /
    List<Brand> findAll(a);

    /** * Search ** based on brand information@param brand
     * @return* /
    List<Brand> search(Brand brand);

    /** * Query brand information based on id **@param id
     * @return* /
    Brand findById(Integer id);

    /** * new brand **@param brand
     */
    void addBrand(Brand brand);

    /** * Change the brand according to the id **@param brand
     */
    void updateBrand(Brand brand);

    /** * Delete brand by id **@param id
     */
    void deleteBrand(Integer id);
}
Copy the code

5. The Service interface implements class invocation

/ * * *@Auther: csp1999
 * @Date: 2020/12/24/17:18
 * @Description: Brand Brand related Service implementation */
@Service
public class BrandServiceImpl implements BrandService {

    @Autowired
    private BrandMapper brandMapper;

    /** * query all brand information **@return* /
    @Override
    public List<Brand> findAll(a) {
        return brandMapper.selectAll();
    }

    /** * Search ** based on brand information@param brand
     * @return* /
    @Override
    public List<Brand> search(Brand brand) {

        // Customize the conditional search object Example
        Example example = new Example(Brand.class);
        // Create a conditional constructor based on the conditional search object example
        Example.Criteria criteria = example.createCriteria();

        // brand is not empty
        if(brand ! =null) {

            // brand.name ! = null Fuzzy search based on brand name:
            // SELECT * FROM tb_brand WHERE name LIKE "% %"
            if(! StringUtils.isEmpty(brand.getName())) {/* * 1. Member attribute name of the Brand object * 2. Placeholder parameter, search criteria */
                criteria.andLike("name"."%" + brand.getName() + "%");
            }

            // brand.letter ! = null Searches based on the first letter of the brand
            // SELECT * FROM tb_brand WHERE name LIKE "% %" AND letter = 'W'
            if(! StringUtils.isEmpty(brand.getLetter())){ criteria.andEqualTo("letter",brand.getLetter()); }}// Perform queries based on custom search objects
        return brandMapper.selectByExample(example);
    }

    /** * Query brand information based on annotation id **@param id
     * @return* /
    @Override
    public Brand findById(Integer id) {
        return brandMapper.selectByPrimaryKey(id);
    }

    /** * new brand **@param brand
     */
    @Override
    public void addBrand(Brand brand) {

        /* * insertSelective concatenates SQL statements based on whether the attribute of the parameter object is empty. * * If the attribute field is empty, it will not be concatenated into the VALUES of the SQL statement. So is updateSelective and Update! * /
        brandMapper.insertSelective(brand);
    }

    /** * Change the brand according to the id **@param brand
     */
    @Override
    public void updateBrand(Brand brand) {

        // Update values whose attributes are not NULL based on the primary key
        brandMapper.updateByPrimaryKeySelective(brand);
    }

    /** * Delete brand by id **@param id
     */
    @Override
    public void deleteBrand(Integer id) { brandMapper.deleteByPrimaryKey(id); }}Copy the code

6. The Controller calls

In front end separation, data interaction is generally conducted in JSON format, so a Result object is encapsulated and returned to the front end:

Result

/ * * *@Auther: csp1999
 * @Date: 2020/12/24/9:26
 * @Description: encapsulates the return result class used by the microservice to return the result to the front end */
@ApiModel(description = "Result", value = "Result")
public class Result<T> {

    /** * succeeds: true operation succeeds /false operation fails */
    @APIModelProperty (value = "Executed successfully,true: successful,false: failed ", Required = true)
    private boolean flag;

    /** * returns the status code */
    @APIModelProperty (value = "Return status code,20000: success,20001: failure,20002: user name or password error,20003: insufficient permission,20004: remote call failure,20005: duplicate operation,20006: no data ", required = true)
    private Integer code;

    /** * returns the message content */
    @APIModelProperty (value = "prompt ", Required = true)
    private String message;

    /** * returns data */
    @APIModelProperty (value = "logical data ", Required = true)
    private T data;

    public Result(boolean flag, Integer code, String message, Object data) {
        this.flag = flag;
        this.code = code;// The status code can be customized
        this.message = message;
        this.data = (T) data;
    }

    public Result(boolean flag, Integer code, String message) {
        this.flag = flag;
        this.code = code;// The status code can be customized
        this.message = message;
    }

    public Result(a) {
        this.flag = true;
        this.code = StatusCode.OK;// The status code can be customized
        this.message = "Operation successful!";
    }
    
    /* The setter/getter method omitted */
}
Copy the code

BrandController

/ * * *@Auther: csp1999
 * @Date: 2020/12/24 / very *@Description: Brand Brand related Controller */
@RestController
@RequestMapping(value = "/brand")
@CrossOrigin // cross-domain annotations
public class BrandController {

    @Autowired
    private BrandService brandService;

    /** * query all brand information **@return* /
    @GetMapping("/brandList")
    public Result<List<Brand>> findAll() {
        // Query information about all brands
        List<Brand> brandList = brandService.findAll();

        / / response results encapsulation: true operation success | StatusCode. OK status code 20000 | | response prompt information to the front end of data
        return new Result<List<Brand>>(true, StatusCode.OK, "Query brand set successful!", brandList);
    }

    /** * search for brand collection by criteria **@param brand
     * @return* /
    @PostMapping("/search")
    public Result<List<Brand>> search(@RequestBody Brand brand) {
        // Call service to implement the query
        List<Brand> brandList = brandService.search(brand);

        / / response results encapsulation: true operation success | StatusCode. OK status code 20000 | | response prompt information to the front end of data
        return new Result<List<Brand>>(true, StatusCode.OK, "Search the brand collection according to the condition succeeded!", brandList);
    }

    /** * Query brand information based on id **@param id
     * @return* /
    @GetMapping("/{id}")
    public Result<Brand> findById(@PathVariable(value = "id") Integer id) {

        // Query the brand based on the ID
        Brand brand = brandService.findById(id);

        / / response results encapsulation: true operation success | StatusCode. OK status code 20000 | | response prompt information to the front end of data
        return new Result<Brand>(true, StatusCode.OK, "According to the id." + id + "Brand query successful!", brand);
    }

    /** * Add brand data **@param brand
     */
    @PostMapping("/addBrand")
    public Result addBrand(@RequestBody Brand brand) {

        // Add new brand
        brandService.addBrand(brand);

        / / response results encapsulation: true operation success | StatusCode. OK status code 20000 | | response prompt information to the front end of data
        return new Result(true, StatusCode.OK, "New brand success!");
    }

    /** * Modify the brand data according to the brand id **@param id
     * @param brand
     * @return* /
    @PutMapping("/updateBrand/{id}")
    public Result updateBrand(@PathVariable(value = "id") Integer id, @RequestBody Brand brand) {

        // Assign the id to the brand
        brand.setId(id);

        // Invoke the Service implementation class
        brandService.updateBrand(brand);

        / / response results encapsulation: true operation success | StatusCode. OK status code 20000 | | response prompt information to the front end of data
        return new Result(true, StatusCode.OK, "Id:" + id + "The brand modification is successful!");
    }

    /** * Delete brand by id **@param id
     * @return* /
    @DeleteMapping("/deleteBrand/{id}")
    public Result deleteBrand(@PathVariable(value = "id") Integer id) {

        // Call service to delete
        brandService.deleteBrand(id);

        / / response results encapsulation: true operation success | StatusCode. OK status code 20000 | | response prompt information to the front end of data
        return new Result(true, StatusCode.OK, "Id:" + id + "Brand deleted successfully!"); }}Copy the code

7. Extension: PageHelper page query

Paging query

The service interface

/** ** ** ** ** ** ** ** **@param currentPage
 * @param pageSize
 * @return* /
PageInfo<Brand> findAllByPage(Integer currentPage, Integer pageSize);
Copy the code

Service interface implementation class

/** ** ** ** ** ** ** ** **@param currentPage
 * @param pageSize
 * @return* /
@Override
public PageInfo<Brand> findAllByPage(Integer currentPage, Integer pageSize) {
    /* * PageHelper.startPage(currentPage,pageSize); This is followed by a query for the Brand object collection * 1. Current page * 2. How many records per page */
    PageHelper.startPage(currentPage, pageSize);
    // Query the brandList collection
    List<Brand> brandList = brandMapper.selectAll();
    // Encapsulates the PageInfo object
    PageInfo<Brand> pageInfo = new PageInfo<>(brandList);
    return pageInfo;
}
Copy the code

controller

/** ** ** ** ** ** ** ** **@paramCurrentPage the currentPage *@paramPageSize Total records per page *@return* /
@GetMapping("/brandList/{currentPage}/{pageSize}")
public Result<PageInfo<Brand>> findAllByPage(@PathVariable(value = "currentPage") Integer currentPage,
                                             @PathVariable(value = "pageSize") Integer pageSize) {
    // Call service to implement paging query
    PageInfo<Brand> pageInfo = brandService.findAllByPage(currentPage, pageSize);
    / / response results encapsulation: true operation success | StatusCode. OK status code 20000 | | response prompt information to the front end of data
    return new Result<PageInfo<Brand>>(true, StatusCode.OK, "Paging query brand collection successful!", pageInfo);
}
Copy the code

Paging + multi-criteria search

The service interface

/** ** paging + multi-conditional search *@param brand
 * @param currentPage
 * @param pageSize
 * @return* /
PageInfo<Brand> searchByPage(Brand brand,Integer currentPage, Integer pageSize);
Copy the code

Service interface implementation class

/** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** *@param brand
 * @param currentPage
 * @param pageSize
 * @return* /
@Override
public PageInfo<Brand> searchByPage(Brand brand, Integer currentPage, Integer pageSize) {
    // 1.
    PageHelper.startPage(currentPage, pageSize);
    // 2. Query data:
    Example brandExample = this.getBrandExample(brand);
    List<Brand> brandList = brandMapper.selectByExample(brandExample);
    // 3. Wrap returns PageInfo:
    PageInfo<Brand> pageInfo = new PageInfo<>(brandList);
    return pageInfo;
}

// query the name of the brand
private Example getBrandExample(Brand brand) {
    // Customize the conditional search object Example
    Example example = new Example(Brand.class);
    // Create a conditional constructor based on the conditional search object example
    Example.Criteria criteria = example.createCriteria();
    // brand is not empty
    if(brand ! =null) {
        // brand.name ! = null Fuzzy search based on brand name:
        // SELECT * FROM tb_brand WHERE name LIKE "% %"
        if(! StringUtils.isEmpty(brand.getName())) {/* * 1. Member attribute name of the Brand object * 2. Placeholder parameter, search criteria */
            criteria.andLike("name"."%" + brand.getName() + "%");
        }
        // brand.letter ! = null Searches based on the first letter of the brand
        // SELECT * FROM tb_brand WHERE name LIKE "% %" AND letter = 'W'
        if(! StringUtils.isEmpty(brand.getLetter())) { criteria.andEqualTo("letter", brand.getLetter()); }}return example;
}
Copy the code

controller

/** ** page + multi-criteria search brand collection **@param brand
 * @param currentPage
 * @param pageSize
 * @return* /
@PostMapping("/search/{currentPage}/{pageSize}")
public Result<PageInfo<Brand>> findAllByPage(@RequestBody Brand brand,
                                             @PathVariable(value = "currentPage") Integer currentPage,
                                             @PathVariable(value = "pageSize") Integer pageSize) {
    // Call service to implement paging query
    PageInfo<Brand> pageInfo = brandService.searchByPage(brand, currentPage, pageSize);
    / / response results encapsulation: true operation success | StatusCode. OK status code 20000 | | response prompt information to the front end of data
    return new Result<PageInfo<Brand>>(true, StatusCode.OK, "Paging + multi-criteria search brand set successful!", pageInfo);
}
Copy the code

If the text is helpful to you! Please give it a thumbs up!