Java study notes---SpringBoot advanced usage

SpringBoot advanced usage

SpringBoot configuration file description

About the configuration file description

Explanation: When the Spring program starts, it needs to load the default configuration file, the default name: application.properties

Modify the character set encoding

Description: The following operations modify the character set format when parsing code in IDEA

Insert picture description here

properties configuration file description

grammar:

​ 1. Data structure key-value structure
​ 2. Writing key=value "key2"="value2"
​ 3. Data type properties are all strings, so there is no need to add the "sign
. 4. Disadvantages configuration information has no hierarchical structure , You must write the full name of the configuration
​ 5. The default character set code IS0-8859-1 when the program loads the pro file through the IO stream

YML configuration file description

#关于YML配置文件说明
# 1.数据结构    key=value
# 2.数据类型    默认都是字符串 如果需要类型转化,则框架已经在内部完成
# 3.yml写法:   1.key: (空格)value  2.有层级结构 编辑时注意
# 4.字符集编码: 默认程序加载时都是UTF-8
server:
  port: 8080
  #项目发布的路径
  servlet:
    #  /缺省值  localhost:8080/jt/xxxx请求路径
    context-path: /

SpringBoot assigns values ​​to attributes

Business description

Note: Because the business needs some attribute information, if it is directly written in the code, the later scalability is not good, so dynamic assignment is required. Since the objects are generally managed by the Spring container, the assignment operation should also have the Spring container Assignment

Edit YML configuration file

server:
  port: 8080
  # 项目发布的路径
  server:
  	# / 缺省值 localhost:8080/jt/xxxx请求路径
    context-path: /
# 2.为属性赋值 hello代表前缀	key=hello.msg
hello:    
	msg: "您好SpringBoot"

Assign values ​​to attributes

@RestController	//向前端返回JSON 特殊格式的字符串
public class HelloController{
    
    //需求:从容器中获取属性数据	springel=spel表达式
    @Value("${hello.msg}")	//自动生成get/set方法
    private String msg; // = “您好SpringBoot”
}

Hot deployment

explain

​ Note: Hot deployment is generally more suitable in the development phase, but this function is generally cancelled during the release phase.

​ Function: When the program is modified for a period of time, the tomcat server will automatically restart

​ Disadvantages: Eclipse is compatible with perfect restart immediately, IDEA completes the restart after 3~5 seconds

Add hot deployment jar package

CV import in the pom.xml file of the project

<!--支持热部署 -->
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-devtools</artifactId>
</dependency>

Modify IDEA configuration

Description: In order to make IDEA automatic hot deployment

Combination key: ctrl + alt + shift + /

Insert picture description here


Insert picture description here

Lombok bag

Annotated automatic generation of Get, Set, toString

<!--	注解式自动生成Get,Set,toString  类似方法	-->
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
		</dependency>

Meaning of self-explanatory notes:

​ @Data is written on the specified class to automatically generate get, set, toString and other methods for the specified class

​ @Accessors(chain = true) open chain loading

​ @NoArgsConstructor no-argument constructor

​ @AllArgsConstructor full parameter construction method

Import the database

Check if the database is available

Enter cmd in the DOS command window to open the command window and enter the command: mysql -u account -p password

Check database service items

Note: Sometimes abnormal situations may occur when the computer is started, causing the mysql database service to fail to start normally, and the display effect indicates that the database connection is abnormal

Check: Check whether the MYSQL service item is available

Spring container

Description: Spring container = HashMap<k,v>

@Controller
public class HelloController{
}
// 实例化:反射机制

SpringBoot integrates MyBatis

Configure the pom.xml file

<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.jt</groupId>
    <artifactId>springboot_demo_2</artifactId>
    <version>1.0-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.0</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <name>springboot_demo_2</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!--支持热部署 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
        </dependency>
        <!--	注解式自动生成Get,Set,toString  类似方法	-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

Prepare the main startup class

package com.jt;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringBootRun {

    public static void main(String[] args) {
        SpringApplication.run(SpringBootRun.class);
    }
}

Solution if the port is occupied after startup

Create an application.yml file in the resources package under the module and enter the following code

server:  port: 8090  #8090是新的端口号   可自指定

Create pojo package

Create a subpackage in the main startup class

This package is used to store the instantiated object classes required by the program.
Insert the picture description here

Add jar to pom.xml

Introduce database driver

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

SpringBoot database connection

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

Spring integrates Mybatis (temporary)

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

Create an application.yml file to introduce data source information

server:  
	port: 8090  
	servlet:    
	context-path: /
spring:  
	datasource:    
	driver-class-name: com.mysql.jdbc.Driver    
	url: jdbc:mysql://127.0.0.1:3306/jtdbserverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf8&autoReconnect=true&allowMultiQueries=true    
	username: root    
	# 密码不能以0开头,如果0开头 则使用"012345"    password: root#Mybatis整合mybatis: #定义别名包  type-aliases-package: com.jt.demo.pojo  mapper-locations: classpath:/mybatis/mappers/*.xml  #开启驼峰映射  configuration:    map-underscore-to-camel-case: true

Summary about Mybatis

What is Mybatis?

Mybatis is the framework of the persistence layer, which mainly interacts with the database. Mybatis encapsulates JDBC internally.

Mybatis calls it a "semi-automated ORM framework"

JDBC source code

package cn.tedu.example.jdbc;

import java.sql.*;
import java.util.Scanner;

/**
 * 测试JDBC
 * 用来把java程序和数据库连接起来,目的是通过java代码操作数据库
 * @author Cloud
 */
public class TestJdbc extends JDBCUtils{
    public static void main(String[] args) {
//        //普通方式
        method();
//        //SQL注入攻击解决方案
        method2();
//        //JDBC连接SQL,java  练习
        method1();
//        查询user表中武洋洋的所有数据
        method3();
//        向dept表中插入数据
        method4();
    }

    private static void method4() {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbctest","root","root");
            String sql = "insert into dept(dname,loc) values(?,?)";
            PreparedStatement ps = con.prepareStatement(sql);
            ps.setString(1,"销售部");
            ps.setString(2,"二区");
            //专门执行增删改的SQL
            ps.executeUpdate(sql);
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }finally {
            try {
                ps.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
            try {
                con.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }

    private static void method3() {
        String[] str = {"jdbc:mysql://localhost:3306/jdbctest","root","root"};
        Connection conn = JDBCUtils.getConnection(str);
        String[] pw1 = {"武洋洋","123456"};
        String str1 = "select id,name,pwd from user where name = ? and pwd = ?";
        JDBCUtils.getPreparedStatement(str1,pw1);
    }

    /**
     * 使用JDBC通过java查询数据库中user表的数据
     */
    private static void method1() {
        try {
            //注册驱动jar包
            Class.forName("com.mysql.jdbc.Driver");
            //连接数据库
            Connection con = DriverManager.getConnection(
                    //域名:服务器名://数据库的端口号/数据库名
                    "jdbc:mysql://localhost:3306/jdbctest",
                    //    数据库账号     数据库密码
                    "root","root");
            //获取传输器
            Statement st = con.createStatement();
            //执行SQL语句
            String sql = "select id,name,pwd from user where name = '武洋洋' and pwd = '123456'";
            ResultSet rs = st.executeQuery(sql);
            //处理|解析结果集
            while(rs.next()){
                String id = rs.getString(1);
                String name = rs.getString(2);
                String pwd = rs.getString(3);
                System.out.println(id+"\n"+name+"\n"+pwd);
            }
            //释放资源
            rs.close();
            st.close();
            con.close();
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 使用JDBC查询 user 表的数据
     */
    private static void method() {
        try {
            //1.注册驱动jar包
            Class.forName("com.mysql.jdbc.Driver");
            //2.连接数据库
//             getConnection(1,2,3)  1是要连接哪个数据库  2是用户名   3是密码
            Connection con = DriverManager.getConnection(
                    //协议:服务器名字://数据库的端口号/数据库名
                    "jdbc:mysql://localhost:3306/jdbctest",
                    "root","root");
            //3.获取传输器
            Statement st = con.createStatement();
            //4.执行SQL
            String sql = "select id,name,pwd from user where name = 'jack' and pwd = '123456'";
            ResultSet rs = st.executeQuery(sql);
            //5.处理|解析结果集
//             遍历user表中的所有数据  next()是用来判断是否有数据的若没有数据则返回false
            while (rs.next()){
                String id = rs.getString(1);
                String name = rs.getString(2);
                String pwd = rs.getString(3);
                System.out.println(id+"\t"+name+"\t"+pwd);
            }
            //6.释放资源
            rs.close();
            st.close();
            con.close();
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }
    }
    /**
      *SQL注入攻击的解决方案
     * 是指当用户只输入数据时,而已包含了特殊的SQL
     *  导致只需要名字不需要输入密码也可以查看所有数据
     *  名字输入后两种值,都会产生SQL攻击问题:jack'#  或  jack' or '1=1
     */
    public static void method2(){
        Scanner sc = new Scanner(System.in);
        //解决SQL注入问题
        try {
            Class.forName("com.mysql.jdbc.Driver");
            String url = "jdbc:mysql://localhost:3306/jdbctest";
            String name = "root";
            String pwd = "root";
            Connection con = DriverManager.getConnection(url,name,pwd);
            //此处的?称为占位符
            String sql = "select id,name,pwd from user where name = ? and pwd = ?";
            PreparedStatement ps = con.prepareStatement(sql);
            ps.setString(1,sc.nextLine());
            ps.setString(2,sc.nextLine());
            ResultSet rs = ps.executeQuery();
            while (rs.next()){
                String id = rs.getString(1);
                String name1 = rs.getString(2);
                String pwd1 = rs.getString(3);
                System.out.println(id+"\t"+name1+"\t"+pwd1);
            }
            //6.释放资源
            rs.close();
            ps.close();
            con.close();
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }

        //暴露SQL注入问题
        try {
            Class.forName("com.mysql.jdbc.Driver");
            String url = "jdbc:mysql://localhost:3306/jdbctest";
            String name = "root";
            String pwd = "root";
            Connection con = DriverManager.getConnection(url,name,pwd);
            Statement st = con.createStatement();
            System.out.println("请输入用户名");
            String n = sc.nextLine();
            System.out.println("请输入密码");
            String p = sc.nextLine();
            String sql = "select id,name,pwd from user where name ='"+n+"'and pwd ='"+p+"'";
            ResultSet rs = st.executeQuery(sql);
            while (rs.next()){
                String id = rs.getString(1);
                String name1 = rs.getString(2);
                String pwd1 = rs.getString(3);
                System.out.println(id+"\t"+name1+"\t"+pwd1);
            }
            //6.释放资源
            rs.close();
            st.close();
            con.close();
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }
    }
}

ORM thinking

Object-relational mapping (English: Object Relational Mapping , ORM for short , or O/RM , or O/R mapping ) is a programming technique used to implement data conversion between different types of systems in object-oriented programming languages . In effect, it actually creates a "virtual object database" that can be used in programming languages . There are many free and paid ORM products, and some programmers prefer to create their own ORM tools.

Summary: Operate the database in an object-oriented manner,

Difficulties: 1. The object should form a one-to-one mapping with the table

​ 2. The attributes in the object should be one-to-one mapping with the fields in the table

classification:

​ 1. Update operation: Handwritten SQL, parameters are generally encapsulated in the form of objects, and then executed through #{Attributes}

​ 2. Query operation: handwritten SQL, the result set is automatically encapsulated

Thinking: Why hasn't Mybatis implemented a fully automated ORM for so many years? ? ?

Reason: Mybatis believes that the execution efficiency of SQL written by oneself is the highest, and it is also more versatile, such as multi-table association.

Summary: Performance issues, if made fully automated and object-oriented, will affect performance

Expand

Fully automated ORM

user object (...) userMapper.insert(user); The automatic program storage configuration is cumbersome

Spring supplement

Spring internal data structure

1. Data structure: Map is understood as a container

2. The content of the data: Key-Value

​ -Key: Generally the first letter of the class name is lowercase HelloController>>>>helloController

​ -Value: generally stores objects that are instantiated through reflection and other mechanisms

​ Map<helloController, controller object>

Singleton: Only one object is stored in the container. The Spring container manages the life cycle of the object, and it lives and dies almost with the container (people are in the tower) Spring container default: singleton object

Many cases: If the user needs to use it, a newly created object is given to the user to use, and the user manages the life cycle of the object.

Bean configuration file description

<bean id="唯一标识" class="类的路径">	与Map集合进行关联	

Regarding environmental code errors

Database problem

Mysql database version: Teacher computer 5.5 higher version database 6.0 or above.

Insert picture description here

IDEA version problem

Modify the path of mybatis

Insert picture description here