SpringBoot-study notes (basic)

1. Concept

Spring Boot is an open source framework for Java applications 用于快速构建based on SpringBoot.Spring框架

  • 简化了Springthe application 配置和部署process;
  • The principles provided 约定大于配置enable developers to focus more on the implementation of business logic.
    /

Spring Boot is not a functional enhancement of Spring, but a way to quickly use Spring .
Problems with Spring:

  1. The configuration is cumbersome : Although Spring's component code is lightweight, its configuration is heavyweight.
  2. Dependency is cumbersome : project dependency management is also time-consuming and labor-intensive;

Spring Boot function

  1. Auto-configuration
    Spring Boot automatically configures the various components of the application, including database connectivity, web development, security, and more, based on the application's dependencies and libraries on the classpath. This can reduce the workload of manual configuration and improve development efficiency.
  2. Starting Dependency
    Spring Boot provides a series of Starter dependencies. By introducing these dependencies, you can quickly integrate commonly used technology stacks and frameworks, such as Spring MVC, Spring Data, JPA, Thymeleaf, etc. Starter dependencies simplify the work of dependency management and version control.
  3. Embedded container
    Spring Boot integrates some commonly used embedded Servlet containers (such as Tomcat, Jetty), and can package applications into executable JAR files or WAR files for easy deployment and operation without additional installation of a separate web server.
    4. Configuration management
    Spring Boot supports a variety of configuration file formats, such as properties, YAML, etc., which can easily manage the configuration information of the application. It also provides features such as property binding and configuration annotations, which simplify the reading and use of configuration.

1.1 SpringBoot quick start

Video: https://www.bilibili.com/video/BV15b4y1a7yG

Implementation steps
① Create Maven project
② Import SpringBoot start-up dependencies
③ Define Controller
④ Write boot class
⑤ Start the test

insert image description here
insert image description here
insert image description here


<?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
<!--		<version>3.1.3</version>-->
		<version>2.7.7</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>

  <!-- Generated by https://start.springboot.io -->
  <!-- 优质的 spring/boot/data/security/cloud 框架中文文档尽在 => https://springdoc.cn -->
	<groupId>com.example</groupId>
	<artifactId>springboot_01_01_quickstart</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>springboot_01_01_quickstart</name>
	<description>springboot_01_01_quickstart</description>
	<properties>
		<java.version>1.8</java.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
			<version>2.7.3</version>
		</dependency>

		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
				<configuration>
					<excludes>
						<exclude>
							<groupId>org.projectlombok</groupId>
							<artifactId>lombok</artifactId>
						</exclude>
					</excludes>
				</configuration>
			</plugin>
		</plugins>
	</build>

</project>

Create the controller class

package com.example.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/test")
public class TestController {
    
    

    @GetMapping
    public String getById(){
    
    
        System.out.println("springboot 启动");
        return "SpringBootRunning";
    }
}

Enable quickstart test
insert image description here
insert image description here

1.2 Comparison between SpringBoot and Spring

class/config file Spring SpringBoot
pom file coordinates manual Tick ​​to add
web3.0 configuration class manual none
configuration class manual none
controller manual manual

1.3 Introduction to pom file coordinates

1.3.1 spring-boot-starter-parent coordinates

spring-boot-starter-parent coordinates

<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.7.7</version>
		<relativePath/>
	</parent>

introduce

  • spring-boot-starter-parent is a parent POM of Spring Boot (the development of SpringBoot programs needs to inherit this coordinate)
  • Defines dependency management, build configuration, and plugin configuration

Advantage

  • Simplified configuration: pring-boot-starter-parent contains many related sub-coordinates or dependencies. These dependencies are libraries and frameworks commonly used in Spring Boot projects, such as Spring core library, Spring Data, Spring MVC, Jackson, etc.
  • Unified management: By using the parent POM, the version of the dependent library used in the project can be managed in a unified manner, thereby avoiding compatibility problems between different projects due to inconsistent dependency versions.
  • Improve efficiency: By using the parent POM, commonly used dependent libraries can be easily added and managed, thereby improving development efficiency.

SpringBoot Start系列
The Spring Boot Start series is a series of starter dependencies provided by Spring Boot to simplify the construction and dependency management of Spring applications

Advantage

  • All dependencies used by the current project are defined to achieve the purpose of reducing configuration;
  • Each Start contains multiple related dependency coordinates according to different functions;
  • It can achieve the purpose of fast configuration and simplified configuration

type:

coordinate illustrate
spring-boot-starter: This is the basic builder for a Spring Boot application, containing Spring Boot's core functionality and basic dependencies.
spring-boot-starter-web: A starter for building web applications, including dependencies such as Spring MVC, Spring Web, Spring Data, and Jackson.
spring-boot-starter-data-jpa: Provides JPA data access abstraction based on Spring Data, which simplifies database operations.
spring-boot-starter-data-rest: Provides a data exposure abstraction based on Spring Data Rest, which can quickly build a RESTful API.
spring-boot-starter-jdbc: Provides a database access abstraction based on Spring JDBC, which simplifies database operations.
spring-boot-starter-amqp: A starter for building messaging applications based on RabbitMQ.
spring-boot-starter-integration: Provides an integration abstraction based on the Spring Integration module, which simplifies business integration development.
spring-boot-starter-test: Dependencies are provided for unit testing, integration testing and end-to-end testing.
spring-boot-starter-thymeleaf Thymeleaf is a template engine, a web development tool that combines templates and data and generates final documents using thymeleaf

1.3.2 spring-boot-starter-web coordinates

spring-boot-starter-web

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

introduce

  • spring-boot-starter-web is a Spring Boot starter coordinate for quickly building a Spring-based Web project.
  • It contains the dependent libraries and configurations required to build web applications, including Spring MVC, Spring Web, Spring Data, Jackson, etc.

Advantage

  • Simplified configuration: By embedding the Servlet container, Spring Boot can simplify the configuration and no longer need to be deployed into the container as a war package. Developers only need to make an executable jar package
  • Automatic configuration: Spring Boot can automatically configure beans according to the classes and jar packages in the current class path. For example, adding a spring-boot-starter-web starter can have web functions without other configuration.
    insert image description here

1.3.3 thymeleaf quick start

Thymeleaf is a Java template engine that can be used to create dynamic web pages and static web pages
Thymeleaf advantages:

  • It appears as an attribute of html to ensure that the complete grammatical structure of html is not destroyed: by directly returning the path of the template file, Thymeleaf can maintain the complete grammatical structure of html to ensure that the page is displayed and rendered correctly.
  • The browser can directly preview the template file without server-side support: Since Thymeleaf can directly return the template file path to the client, the browser can directly open and preview the template file without server-side support.

using spring-boot-starter-thymeleaf

step:

  1. import coordinates
  2. Write the controller class
  3. Configure the web page prefix and suffix in the application file
  4. Create a templates directory in the resource to store html files (change the resource from a normal directory to a source code directory)
  5. test

1. Import coordinates

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

2. Write the controller class

package com.example.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;


@Controller
public class TestController {
    
    
    @RequestMapping("/test")
    public String thymeleaf(Model model){
    
    
        model.addAttribute("name","nini");
        return "hello";//返回模板名,与模板文件名对应
    }
}

3. Configure the web page prefix and suffix in the application file

#配置网页前缀和后缀
#配置网页前缀和后缀
#classpath:/templates/,表示模板文件位于项目的/src/main/resources/templates/目录下。
#.html,表示模板文件的扩展名为.html。

spring.thymeleaf.prefix = classpath:/templates/
spring.thymeleaf.suffix = .html 

4. Create a templates directory in the resource to store html files (change the resource from a normal directory to a source code directory)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>hello_jaja_thy</h1>
<!--th:text="${title}"是一个Thymeleaf表达式语言(TEL)表达式。它表示将模板中的文本内容替换为Spring控制器传递给模板的模型属性。-->
<p th:text="'hello:'+${name}" ></p>
</body>
</html>

insert image description here
5. Test
insert image description here

1.4 Boot class

Startup class:

  • is the execution entry point of the entire program
  • Function: Initialize a Spring container, scan the package where the boot class is located to load beans
package com.example;

import com.example.controller.TestController;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;


//SpringBootApplication:
//Spring Boot提供的核心注解,它包含了@Configuration、@EnableAutoConfiguration、@ComponentScan等注解的功能。
@SpringBootApplication
public class Springboot0101QuickstartApplication {
    
    

	public static void main(String[] args) {
    
    

//SpringApplication.run方法来启动Spring Boot应用程序
		ConfigurableApplicationContext context = SpringApplication.run(Springboot0101QuickstartApplication.class, args);
		TestController bean = context.getBean(TestController.class);
		System.out.println(bean);
	}

}

1.5 modify configuration

Configuration documentation:
https://docs.spring.io/spring-boot/docs/current/reference/html/application-properties.html#appendix.application-properties

Query method
insert image description here
insert image description here
Find configuration
insert image description here

SpringBoot configuration method

  • application.properties
  • application.yml
  • application.yaml
--------------------application.properties------------------------
server.port=8080  
spring.datasource.url=jdbc:mysql://localhost:3306/mydb  
spring.datasource.username=root  
spring.datasource.password=password

---------------------application.yml(主流)/application.yaml-------------------------------
server:  
  port: 8080  
spring:  
  datasource:  
    url: jdbc:mysql://localhost:3306/mydb  
    username: root  
    password: password

1. Modify the port configuration
Add the port to the application.properties file under resources

#修改服务器端口
server.port=80

Restart the server
insert image description here
2 to modify the banner
banner is to start the picture of springboot

#修改banner
#关闭
spring.main.banner-mode=off

3. Modify log

#日志
#只调错误的
logging.level.root=error

1.6 Read configuration

1.6.1 Read configuration information

server:
  port: 81

@Value(value = "${server.port}"):
This annotation is used to inject the value of the environment variable server.port into the member variable port of the class. Spring's annotation @Value is used here, which can inject external configuration properties into Spring Bean.

package com.example.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/test")
public class TestController {
    
    


    @Value(value = "${server.port}")
    private Integer port;

    @GetMapping
    public String getById(){
    
    
        System.out.println("springboot 启动");
        System.out.println("当前的端口:"+port);
        return "SpringBootRunning";
    }
}

insert image description here


Method 2: Load all configurations first, and then read the required


    //加载所有配置
    @Autowired
    private Environment env;
    
    @GetMapping
    public String getById(){
    
    
        System.out.println("springboot 启动");
        System.out.println("当前的端口:"+env.getProperty("server.port"));
        return "SpringBootRunning";
    }

1.6.2 Read configuration information and create classes for encapsulation

step:

  1. Create a class to encapsulate the corresponding data in the yaml file
  2. Define the beans controlled by Springboot
  3. specify specific attributes
package com.example;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

//1.创建类用于封装yaml文件中对应的数据
//2. 定义Springboot管控的bean
@Component

//3.指定特定的属性
@ConfigurationProperties(prefix = "datasource")
@Data
public class MyDataSource {
    
    
    private String driver;
    private String url;
    private String username;
    private String password;


}

test:

@Autowired
    private MyDataSource myDataSource;

    @GetMapping
    public String getById(){
    
    
        System.out.println("springboot 启动");
        System.out.println(myDataSource);
        return "SpringBootRunning";
    }

insert image description here

1.7 Integrate third-party technology

1.7.1 Integrating JUnit

Introduction
JUnit is a Java language unit testing framework for writing and running repeatable tests. It is an instance of xUnit, a unit testing framework system, and can be used for unit testing (that is, white box testing).

step:

  1. Import the starter corresponding to the test
  2. The test class is decorated with @SpringBootTest
  3. Add objects to test using autowiring
package com.example.dao;

public interface BooDao {
    
    
    public void save();
}
-----------------------------------------------------
package com.example.dao.impl;

import com.example.dao.BooDao;
import org.springframework.stereotype.Repository;

//@Repository是一个注解,用于标识数据访问对象(DAO)组件
@Repository
public class BookDaoImpl implements BooDao {
    
    
    @Override
    public void save() {
    
    
        System.out.println("book dao is runing");
    }
}
--------------------------------------------------
package com.example;

import com.example.dao.BooDao;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class Springboot0101QuickstartApplicationTests {
    
    

	//1.注入要测试的对象
	@Autowired
	private BooDao booDao;

	//02.执行要测试的对应的方法
	@Test
	void contextLoads() {
    
    
		System.out.println("执行测试");
		booDao.save();
	}
}


insert image description here

1.7.1 Integrate Mybatis

step:

  1. Import the corresponding starter;
  2. Configuration related information;
  3. Define the data layer interface and mapping configuration;
  4. Inject the dao interface into the test class to test the function;

1. Import the corresponding starter

<dependency>
			<groupId>org.mybatis.spring.boot</groupId>
			<artifactId>mybatis-spring-boot-starter</artifactId>
			<version>2.2.0</version>
		</dependency>

		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<scope>runtime</scope>
		</dependency>

2. Configuration related information

spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: dbc:mysql://localhost:3306/db1
    username: root
    password: 123456

3. Define the data interface layer and mapping layer

package com.example.domain;


import lombok.Data;

@Data
public class User {
    
    
    private int id;
    private String username;
    private String password;
}

-----------------------------------------------------------
package com.example.dao;

import com.example.domain.User;
import org.apache.ibatis.annotations.*;

import java.util.List;

//用户增删改查接口
@Mapper
public interface UserDao {
    
    

    @Insert("INSERT INTO tb_user values (null,#{username},#{password})")
    public void save(User user);

    @Update("UPDATE tb_user set username=#{username},password=#{password} where id=#{id}")
    public void update(User user);

    @Delete("DELETE from tb_user where id = #{id}")
    public void delete(Integer id);

    @Select("SELECT * FROM tb_user")
    public List<User> selectAll();

    @Select("SELECT * FROM tb_user WHERE id=#{id}")
    public User selectById(Integer id);

}

4. Write test class

package com.example;

import com.example.dao.BooDao;
import com.example.dao.UserDao;
import com.example.domain.User;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.List;

@SpringBootTest
class Springboot0101QuickstartApplicationTests {
    
    

	//1.注入要测试的对象

	@Autowired
	private UserDao userDao;

	//02.执行要测试的对应的方法
	@Test
	void contextLoads() {
    
    
		System.out.println("执行测试");
		List<User> users = userDao.selectAll();
		System.out.println(users);
	}


}

insert image description here

1.7.1 Integrate Mybatis-Plus

Mybatis和Mybatis-plus有什么区别?
- 导入坐标不同
- 数据层实现简化

step:

  1. Import the corresponding starter;
  2. Define data layer interface and mapping configuration, inherit BaseMapper
  3. Define the data layer interface and mapping configuration;
  4. Inject the dao interface into the test class to test the function;
<dependency>
			<groupId>com.baomidou</groupId>
			<artifactId>mybatis-plus-boot-starter</artifactId>
			<version>3.4.3</version>
		</dependency>
@Mapper
public interface UserDaoPlus extends BaseMapper<User> {
    
    

Others are similar to mybatis
insert image description here

1.7.1 Druid integration

Address: https://blog.csdn.net/qq_47436772/article/details/115185046

Druid is a distributed data storage and query system designed to support real-time data analysis.

  • Druid is one of Alibaba's open source platforms 数据库连接池实现, combining the advantages of C3P0, DBCP and other DB pools, and adding log monitoring at the same time
  • It adopts a distributed architecture, can handle large-scale data streams, and provides real-time aggregation and query functions.
<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.2.5</version>
</dependency>

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/db1
    username: root
    password: 123456
    type: com.alibaba.druid.pool.DruidDataSourceC3P0Adapter

insert image description here

2. Data layer

2.1 SSMP integration - basic database CRUD

step:

  1. import coordinates
  2. Configuration related information
  3. Write domain/dao file
  4. implement test
<?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.7.7</version>
		<relativePath/>
	</parent>


	<groupId>com.example</groupId>
	<artifactId>springboot_01_01_quickstart</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>springboot_01_01_quickstart</name>
	<description>springboot_01_01_quickstart</description>
	<properties>
		<java.version>1.8</java.version>
	</properties>

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

		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<optional>true</optional>
		</dependency>

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

		<dependency>
			<groupId>org.mybatis.spring.boot</groupId>
			<artifactId>mybatis-spring-boot-starter</artifactId>
			<version>2.2.0</version>
		</dependency>

		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<scope>runtime</scope>
		</dependency>

		<dependency>
			<groupId>com.baomidou</groupId>
			<artifactId>mybatis-plus-boot-starter</artifactId>
			<version>3.4.3</version>
		</dependency>

		<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>druid</artifactId>
			<version>1.2.5</version>
		</dependency>


	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
				<configuration>
					<excludes>
						<exclude>
							<groupId>org.projectlombok</groupId>
							<artifactId>lombok</artifactId>
						</exclude>
					</excludes>
				</configuration>
			</plugin>
		</plugins>
	</build>

</project>

server:
  port: 81



spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/db1
    username: root
    password: 123456
    type: com.alibaba.druid.pool.DruidDataSource

mybatis-plus:
  global-config:
    db-config:
      table-prefix: tb_user
package com.example.domain;


import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;

@Data
@TableName(schema = "db1", value = "tb_user")
public class User {
    
    
    private int id;
    private String username;
    private String password;
}
-----------------------------------------------------------
package com.example.dao;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.domain.User;
import org.apache.ibatis.annotations.*;

import java.util.List;

//用户增删改查接口
@Mapper
public interface UserDaoPlus extends BaseMapper<User> {
    
    

}


test

package com.example.dao;

import com.example.domain.User;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.List;

@SpringBootTest
public class UserDaoTastCase {
    
    
    @Autowired
    private UserDaoPlus userDaoPlus;



    @Test
    void testGetById(){
    
    
        User user = userDaoPlus.selectById(1);
        System.out.println("根据id查用户");
        System.out.println(user);
    }

    @Test
    void testDelete(){
    
    
        userDaoPlus.deleteById(2);
        System.out.println("删除用户");
    }
}

insert image description here
insert image description here

2.2 Debug log

Open the log in the configuration mode, and set the log output mode to standard output

mybatis-plus:
  global-config:
    db-config:
      table-prefix: tb_user
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

insert image description here

2.3 Pagination

step

  1. Use IPage to encapsulate paging data
  2. The paging operation relies on the MyBatisPlus paging interceptor to implement the function
  3. Check and execute SQL statements with the help of MyBatisPlus logs
@Test
void testGetPage(){
    
    
	IPage page = new Page(1,5);
	bookDao.selectPage(page,null);
}

insert image description here

All data in the paging operation is encapsulated in the IPage object

  • Data; current page value; total amount of data per page; maximum page number value; total amount of data;

insert image description here
Use MyBatisPlus interceptor to implement conditional restrictions

package com.example.config;

import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MpConfig {
    
    
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor(){
    
    
        //1.定义Mp拦截器
        MybatisPlusInterceptor mpInterceptor = new MybatisPlusInterceptor();
       
        //2.添加具体的拦截器
        mpInterceptor.addInnerInterceptor(new PaginationInnerInterceptor());
        return mpInterceptor;
    }
}

run again
insert image description here

2.4 Condition query

step

  1. Use QueryWrapper object to encapsulate query conditions
  2. It is recommended to use the LambdaQueryWrapper object
  3. All query operations are encapsulated into method calls
  4. Query conditions support dynamic condition assembly
//使用QueryWrapper对象封装查询条件,推荐使用LambdaQueryWrapper对象,所有查询操作封装成方法调用
    @Test
    void testGetByCondition(){
    
    
        IPage page = new Page(1,10);
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(User::getUsername,"tudou");
        userDaoPlus.selectPage(page, wrapper);
    }

    @Test
    void testGetByConditions(){
    
    
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.like("password","888");
        userDaoPlus.selectList(userQueryWrapper);
    }

insert image description here
insert image description here

3. Business layer

3.1 Business layer definition

  • interface
  • Implementation class
package com.example.service;

import com.example.domain.User;

import java.util.List;

public interface UserService {
    
    
    boolean save(User user);
    boolean delete(Integer id);
    boolean update(User user);
    User getById(Integer id);
    List<User> getAll();
    
}

package com.example.service.impl;

import com.example.dao.UserDaoPlus;
import com.example.domain.User;
import com.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

public class UserServiceImpl implements UserService {
    
    

    @Autowired
    UserDaoPlus userDaoPlus;

    @Override
    public boolean save(User user) {
    
    
        return userDaoPlus.insert(user)>0;
    }

    @Override
    public boolean delete(Integer id) {
    
    
        return userDaoPlus.deleteById(id)>0;
    }

    @Override
    public boolean update(User user) {
    
    
        return userDaoPlus.updateById(user)>0;
    }

    @Override
    public User getById(Integer id) {
    
    
        return userDaoPlus.selectById(id);
    }

    @Override
    public List<User> getAll() {
    
    
        return userDaoPlus.selectList(null);
    }
}

test definition

package com.example.service;

import com.example.domain.User;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
public class UserServiceTestCase {
    
    
    @Autowired
    private UserService userService;

    @Test
    void testGetById(){
    
    
        userService.getById(7);
    }

    @Test
    void testGetAll(){
    
    
        userService.getAll();
    }

    @Test
    void testInsert(){
    
    
        User user = new User();
        user.setUsername("新生");
        user.setPassword("202392");
        userService.save(user);
    }
}

Test Results

3.2 Rapid development of the business layer

  • Use MyBatisPlus to provide a common interface for the business layer (ISerivce) and a common implementation class for the business layer (ServiceImpl<M,T>)
  • Do function overloading or function addition on the basis of common classes

interface

package com.example.service;

import com.baomidou.mybatisplus.extension.service.IService;
import com.example.domain.User;

import java.io.Serializable;

//定义业务层接口
public interface IUserService extends IService<User> {
    
    
    @Override
    default boolean save(User entity) {
    
    
        return IService.super.save(entity);
    }

    @Override
    default boolean removeById(Serializable id) {
    
    
        return IService.super.removeById(id);
    }

    @Override
    default boolean updateById(User entity) {
    
    
        return IService.super.updateById(entity);
    }

    @Override
    default User getById(Serializable id) {
    
    
        return IService.super.getById(id);
    }
}

interface implementation class

package com.example.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.dao.UserDaoPlus;
import com.example.domain.User;
import com.example.service.IUserService;
import org.springframework.stereotype.Service;

@Service
public class IUserServiceImpl extends ServiceImpl<UserDaoPlus, User> implements IUserService {
    
    

}

test

package com.example.service;

import com.example.domain.User;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
public class UserServiceTestCase {
    
    
    @Autowired
    private IUserService iUserService;

    @Test
    void testGetById(){
    
    
        iUserService.getById(1);
    }

    @Test
    void testInsert(){
    
    
        User user = new User();
        user.setUsername("又梨");
        user.setPassword("221133");
        iUserService.save(user);

    }

    @Test
    void deleteTest(){
    
    
        iUserService.removeById(7);
    }
}

4. Presentation layer

4.1 Definition of Presentation Layer

  1. Create a presentation layer interface based on Restful
    Add: POST
    Delete: DELETE
    Modify: PUT
    Query: GET
  2. Receive parameter
    Entity data: @RequestBody
    Path variable: @PathVariable
package com.example.controller;

import com.example.domain.User;
import com.example.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {
    
    
    @Autowired
    private IUserService userService;

    @GetMapping
    List<User> getAll(){
    
    
        return userService.list();
    }

    @GetMapping("/{id}")
    User getById(@PathVariable Integer id){
    
    
        return userService.getById(id);
    }

    @PostMapping
    Boolean save(@RequestBody User user){
    
    
        return userService.save(user);
    }
}

insert image description here
insert image description here
insert image description here

4.2 Message consistency processing

  • Design the model class of the result returned by the presentation layer, which is used to unify the data format between the backend and the frontend, also known as the frontend and backend data protocol.
  • The presentation layer interface uniformly returns value type results
package com.example.controller;

import lombok.Data;

//返回结果的模型类
@Data
public class ResultModel {
    
    
    private Boolean flag;
    private Object data;

    public ResultModel() {
    
    
    }

    public ResultModel(Boolean flag) {
    
    
        this.flag = flag;
    }

    public ResultModel(Boolean flag, Object data) {
    
    
        this.flag = flag;
        this.data = data;
    }
}

package com.example.controller;

import com.example.domain.User;
import com.example.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {
    
    
    @Autowired
    private IUserService userService;

    @GetMapping
    ResultModel getAll(){
    
    
        List<User> list = userService.list();
        return new ResultModel(true,list);
    }

    @GetMapping("/{id}")
    ResultModel getById(@PathVariable Integer id){
    
    
        User byId = userService.getById(id);
        return new ResultModel(true,byId);
    }

    @PostMapping
    ResultModel save(@RequestBody User user){
    
    
        boolean save = userService.save(user);
        return new ResultModel(save);
    }
}

insert image description here
insert image description here

4.3 Front-end and back-end joint debugging

  • Pages belong to the front-end server in the front-end and back-end separation structure design
  • The pages in the single project are placed in the static directory under the resources directory (clean is recommended)
    insert image description here

insert image description here

Vue.js is a popular JavaScript framework for building user interfaces.
Its core idea is componentization, which is to decompose an application into a series of reusable components that can be combined to build more complex applications.

  • As a front-end framework, Vue.js is mainly responsible for processing user interface and user interaction, converting user operations into data and displaying them.
    In front-end development, Vue.js acts as the view layer, interacts with the business logic layer, receives data from the business logic layer, and displays it on the page. At the same time, user operations can also be converted into data and sent to the business logic layer for processing.

<script>
    var vue = new Vue({
    
    
        el: '#app',
        data:{
    
    
            dataList: [],//当前页要展示的列表数据
            dialogFormVisible: false,//添加表单是否可见
            dialogFormVisible4Edit:false,//编辑表单是否可见
            formData: {
    
    },//表单数据
            rules: {
    
    //校验规则
                type: [{
    
     required: true, message: '图书类别为必填项', trigger: 'blur' }],
                name: [{
    
     required: true, message: '图书名称为必填项', trigger: 'blur' }]
            },
            pagination: {
    
    //分页相关模型数据
                currentPage: 1,//当前页码
                pageSize:10,//每页显示的记录数
                total:0//总记录数
            }
        },

        //钩子函数,VUE对象初始化完成后自动执行
        created() {
    
    
        },

        methods: {
    
    
            //列表
            getAll() {
    
    
            },

            //弹出添加窗口
            handleCreate() {
    
    
            },

            //重置表单
            resetForm() {
    
    
            },

            //添加
            handleAdd () {
    
    
            },

            //取消
            cancel(){
    
    
            },
            // 删除
            handleDelete(row) {
    
    
            },

            //弹出编辑窗口
            handleUpdate(row) {
    
    
            },

            //修改
            handleEdit() {
    
    
            },

            //分页查询

            //切换页码
            handleCurrentChange(currentPage) {
    
    
            },

            //条件查询
        }
    })

</script>

A hook function
is a special function whose main role is to deal with intercepting function calls or events or messages passed between software components. Hook functions can be used to handle specific events, or execute custom logic before and after specific function calls.

insert image description here

/钩子函数,VUE对象初始化完成后自动执行
        created() {
    
    
            this.getAll();
        },

        methods: {
    
    
            //列表
            getAll() {
    
    
                console.log("run")
                //发送异步请求
                axios.get("/user").then((res)=>{
    
    
                    console.log(res.data);
                });

            },

insert image description here

4.4 Page List Data Display

Return the query data to the page, and use the front-end data two-way binding for data display

 //钩子函数,VUE对象初始化完成后自动执行
        created() {
    
    
            this.getAll();
        },

        methods: {
    
    
            //列表
            getAll() {
    
    
                //发送异步请求
                axios.get("/user").then((res)=>{
    
    
                    this.dataList=res.data.data;
                });

            }

List
insert image description here

4.5 List operations

  1. The request method uses POST to call the background corresponding operation
  2. Dynamically refresh the page to load data after the adding operation
  3. Depending on the operation result, the corresponding prompt information will be displayed
  4. Clear form data when popup adds Div

Add
insert image description here

//弹出添加窗口
            handleCreate() {
    
    
                this.dialogFormVisible = true;
            },

insert image description here

clear data

resetForm() {
    
    
this.formData = {
    
    };
},
//弹出添加窗口
handleCreate() {
    
    
this.dialogFormVisible = true;
this.resetForm();
}

Add to
insert image description here

            //添加
            handleAdd () {
    
    
                //发送异步请求
                axios.post("/user",this.formData).then((res)=>{
    
    
                         //如果操作成功,关闭弹层,显示数据
                    if(res.data.flag){
    
    
                        this.dialogFormVisible = false;
                        this.$message.success("添加成功");
                    }else {
    
    
                        this.$message.error("添加失败");
                    }
                }).finally(()=>{
    
    
                    this.getAll();
                });
            },

insert image description here
insert image description here
insert image description here

cancel adding

//取消
cancel(){
    
    
this.dialogFormVisible = false;
this.$message.info("操作取消");
},

insert image description here

Guess you like

Origin blog.csdn.net/meini32/article/details/132544107