(springboot 03) day52javaEE basic missing

1. Paging query.

//Configure Paging Interceptors
@Configuration
public class MybatisPlusConfig {
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor(){
        //1 Create MybatisPlus Interceptor interceptor object
        MybatisPlusInterceptor mpInterceptor=new MybatisPlusInterceptor();
        //2 Add Paging Interceptor
        mpInterceptor.addInnerInterceptor(new PaginationInnerInterceptor());
        return mpInterceptor;
    }
}
    //paging
    @Test
    public void testFindByPage() {
        //1. Set Paging Conditions
        Integer pageNum = 2;
        Integer pageSize = 3;
        Page<User> page = new Page<>(pageNum, pageSize);

        //2. Set query criteria
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.gt(User::getAge, 1);

        //3. Paging Query
        //SELECT id,name,password,age,tel FROM user WHERE (age > 1) LIMIT 3,3
        page = userMapper.selectPage(page, wrapper);

        //4. Paging results
        System.out.println("Total number of bars:" + page.getTotal());
        System.out.println("Total pages:" + page.getPages());
        System.out.println("Current page data:" + page.getRecords());
        System.out.println("Current page number value:" + page.getCurrent());
        System.out.println("Number of displays per page:" + page.getSize());
    }

2. There is a bug: the time to modify the categorized dishes is not updated: the update time is not filled:

The reason is that mybatis and mybatisplus are mixed.

The persistence layer passes xml, generates sql, and then populates the fields.

Because dynamic SQL is written in xml, it is possible that an auto-fill field is empty and filtered by if judgement, resulting in no such field in sql, so it cannot be filled. Causes a data not to be updated.

3.LambdaQueryWrapper Query Conditions Encapsulation Object

Analyzing whether a conditional query or a primary key query is the first step, the primary key operation is basically a simple operation without writing wrapper.

4.tomcat encoding and decoding: omcat uses iso-8859-1 by default to decode

Encoding issues with http get
Website: http://www.baidu.com/ Junshan? name=Junshan

It is roughly divided into three parts:

scheme Agreement:http
uri:www.baidu.com/Junshan
queryString Request parameters:name=Junshan

The next two sections require attention to coding issues

For uri, the default decoding method for URI in tomcat is to decode by iso-8859-1, setting up the server. The URIEncoding property of connector in XML is UTF-8 to solve. This way tomcat will resolve URI by default with utf-8.

For queryString request parameters, the encoding method is related to the ContentType of the http header. By default, iso-8859-1 is also used in tomcat to decode and set the server. The useBodyEncodingForURI property in XML is true, and it will decode according to the corresponding encoding specified by the contentType in the request header. Or through request.setCharacterEncoding("UTF-8"); Sets the decoding of the request parameters.
Original Link: https://blog.csdn.net/jdbdh/article/details/81151331

5. How efficient is joint query of multiple tables and multiple queries of single tables?

Single sheet efficiency is high.

Multi-table join queries and single-table queries are almost as efficient when the data volume is small.

If the amount of data is large enough, it must be more efficient to query multiple forms.

In some large companies, multi-table join queries are disabled because once the amount of data is large enough, multi-table join queries are slow and not conducive to query optimization for sub-database tables.

6. The advantages and disadvantages of reshaping an associated query:

Many high-performance applications decompose the associated queries, query each table once, and then associate the results in the application.
1) Make the cache more efficient
Many applications can easily cache the corresponding result objects of a form query. In addition, for MySQL's query cache, if a table in the association changes, the query cache cannot be used, and after splitting, if a table rarely changes, queries based on that table can reuse the query cache results.
2) Reduce Lock Competition
Once the query is broken down, executing a single query reduces lock competition.
3) Easy to split and expand databases
Relevance at the application level makes it easier to split up databases and achieve high performance and scalability.
4) Improve query efficiency
Queries themselves may also be more efficient

5) Disadvantages of reconstructing queries by decomposing associated queries
Originally a query, but here has become more than one query, returning the same results.
Original Link: https://blog.csdn.net/qq_27474555/article/details/103760985

7. Is fuzzy query efficient, learn sql tuning??

Not high. Learn about sql tuning.

8.What is a lang3 package?

Open source toolkit.

Lang3 is a toolkit released by the Apache Commons team that requires jdk versions above 1.5. It fully supports the Java 5 feature as opposed to lang, eliminating some of the older API s. This version is not compatible with older versions, so rename it lang3 to avoid conflicts

The Lang package is obsolete, so don't use it later. Use lang3 instead

Original Link: https://blog.csdn.net/f641385712/article/details/82468927

9. Sets make non-empty judgments, should each layer make non-empty judgments?

I think the main thing is to make non-empty judgments at the business level.

[Recommendation] Preventing NPE is a basic accomplishment for programmers. Note the scenarios in which NPE occurs:
1) The return type is the basic data type. When returning wrapped objects of data type, automatic unboxing may result in NPE.
Counter example: public int f() {return Integer object}, if null, automatically unboxes and throws NPE.
2) The query result of the database may be null.
3) Elements in a collection may be null even if they are isNotEmpty.
4) When a remote call returns an object, null pointer judgment is always required to prevent NPE.
5) For data obtained in Session, NPE checks are recommended to avoid null pointers.
6) Cascade call obj.getA().getB().getC(); A series of calls can easily produce NPE.
Example: Use JDK8's Optional class to prevent NPE problems.

10. Take a look at the packaging principle of mybatis:

1) Create a result object through reflection with all its attributes as default values. For example, if the result is an entity object, then the object will be created through a parameterless constructor with all its attributes generally empty, and if the result is a List, an empty List will be created
2) assign values to the properties of the result object, which is also reflected here to find the set method assignment

11.Can mybatiplus implement join table queries

No, only form queries can be implemented.

12. How to dock with third parties, such as Ali Cloud Object Storage OSS

Look at the product documentation:

1) Install the SDK (Software Development Kit) to introduce dependencies through maven.

2) Initialization and Quick Start, according to the documentation prompt, find the required business docking code, do a demoTest, and test.

3) Find the appropriate code scheme, write the relevant tool classes, and config file yaml.

4) Write out the logic code in the project using the tool class.

13.xxxxtemplet. Java, typically a tool class for manipulating storage systems.

package com.itheima.reggie.common;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.ObjectMetadata;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

//Ali Storage Tool Class
@Component
@ConfigurationProperties(prefix = "reggie.oss")//Read configuration information
@Data
public class OssTemplate {

    private String key; //Access key
    private String secret;//Access Key
    private String endpoint;//Endpoint
    private String bucket;//Bucket name
    private String url;//Access Domain Name

    //File Upload
    public String upload(String fileName, InputStream inputStream) {

        //Create Client
        OSS ossClient = new OSSClientBuilder().build(endpoint, key, secret);

        //Set the final path and name of the file
        String objectName = "images/" + new SimpleDateFormat("yyyy/MM/dd").format(new Date())
                + "/" + System.currentTimeMillis() + fileName.substring(fileName.lastIndexOf("."));

        //meta Set Request Header, Resolve Access Picture Address Direct Download
        ObjectMetadata meta = new ObjectMetadata();
        meta.setContentType(getContentType(fileName.substring(fileName.lastIndexOf("."))));

        //upload
        ossClient.putObject(bucket, objectName, inputStream, meta);

        //Close Client
        ossClient.shutdown();

        return url + "/" + objectName;
    }

    //File Suffix Processing
    private String getContentType(String FilenameExtension) {
        if (FilenameExtension.equalsIgnoreCase(".bmp")) {
            return "image/bmp";
        }
        if (FilenameExtension.equalsIgnoreCase(".gif")) {
            return "image/gif";
        }
        if (FilenameExtension.equalsIgnoreCase(".jpeg") ||
                FilenameExtension.equalsIgnoreCase(".jpg") ||
                FilenameExtension.equalsIgnoreCase(".png")) {
            return "image/jpg";
        }
        return "image/jpg";
    }
}

14. File upload.

Configuration file upload parser

spring:
  servlet:
    multipart:
      max-request-size: 100MB # Maximum request file size, default 10MB
      max-file-size: 10MB # Single request file size, default 1MB

(2) Write file upload code

package com.itheima.reggie.controller;

import com.itheima.reggie.common.OssTemplate;
import com.itheima.reggie.common.ResultInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
public class FileController {

    @Autowired
    private OssTemplate ossTemplate;

    //File Upload
    //Note: Parameter type MultipartFile, parameter name and front-end request name are saved identical
    @PostMapping("/common/upload")
    public ResultInfo uploadFile(MultipartFile file) throws IOException {
        if (file.getSize() > 0){
            //1. Upload the received files to Ali Cloud using OssTemplate
            String filePath = ossTemplate.upload(file.getOriginalFilename(), file.getInputStream());
            //2. Access address returned to front end after upload
            return ResultInfo.success(filePath);
        }
        return ResultInfo.error("File upload failed");
    }
}

15.yaml file, pay attention to the format, new configuration, need fixed format writing.

16.Notes after uploading documents:

Note: The parameter type MultipartFile, parameter name and front-end request name are saved identical.

17. Entity classes for data synthesis from multiple tables:

Find the primary table based on the primary key.

Fields on other tables remember to use the primary key: @TableField(exist = false)

18.mybatis primary key return

Ability to set primary key return when adding operations 
    useGeneratedKeys: tell mybatis We need to use mysql Primary key generated at bottom,To make mybatis Come back to us
    keyProperty: Assign the value of the returned primary key to the specified property of the incoming parameter
    <insert id="save" parameterType="com.itheima.pojo.User"
            useGeneratedKeys="true" keyProperty="uid">
        insert into user values(null,#{name},#{password},#{email},#{birthday})
    </insert>

19. When do I need to turn on transaction control???

At the business level, transactions need to be controlled if a method performs additions and deletions on multiple tables at the same time.

20. Consider multiple updates of a foreign key:

Delete all according to the foreign key, then insert according to the foreign key.

21.@ConfigurationProperties(prefix = "reggie.oss")//What does prefix mean by reading configuration information?

22.controller tries not to write too much. Everything encapsulated by objects is put in the service layer.

controller layer is a control layer in MVC design. Designed to accept and respond to requests; So it's as light as possible to avoid writing code that involves business processing.

23.Note: File upload - When you click on the upload picture, it will be uploaded to the Aliyun server instead of clicking on Save.

Upload Ali Cloud, then return to the path of the picture, and save the path to the database.

24.What is the method name for the three-tier architecture?

1) Dao Interface Naming: The method name here should best correspond to the sql statement, which is most direct. It then indicates that the condition uses By as a preposition, and that the query list is prefixed with list.
Insert: insert
batchInsert: Bulk Insert
selectOne: Query a data
selectById: Query passes through xx condition
Count: count
selectList: Query multiple data
Update: update
deleteById: Delete, by some conditions

2) Service interface naming: here is to solve human thinking, query is find, add is add, delete is remove, modify is modify. Then the condition also uses by, using the list suffix a lot.
Add: add data
findById: Find, or query
findByXXX: Find
findXXXList: Bulk Find
modify:Modify
remove: Simple delete

3) controller layer belongs to control layer in MVC design; Designed to accept and respond to requests; So it's as light as possible to avoid writing code that involves business processing.

Other Naming Specifications
All lowercase project names.
Package names are all lowercase.
Class name: Camel, for example: UpperCamelCase
Variable name, method name: hump: lowerCamelCase
Constant names are all capitalized: public static final int REQUEST_KEY_CODE =1;
All naming rules must follow the following rules:
Names can only consist of letters, numbers, underscores, $symbols.
You cannot start with a number.
Names cannot use keywords in Java.
No Chinese or Pinyin naming is allowed.
Original Link: https://blog.csdn.net/qq_42031483/article/details/107561307

25. Whose account password is the password for read and write access???

26.What is the name of the controller layer method?

Keywords: Java Spring Spring Boot

Added by wulfgar on Tue, 15 Feb 2022 19:22:23 +0200