Advance d usage of Spr ing Boot
SpringBoot configuration file description
About the configuration file description
Explanation: When the Spring program st arts, it needs to load the default configuration file, the default name: application.properties
Modify character set encoding
Note: The following operations modify the character set format when parsing code in IDEA
properties configuration file description
grammar:
1. Data structure key-value structure
2. Writing key=value “key2”=“value2”
3. Data type The data types of properties are all strings, so there is no need to add a ""
4. Disadvantages The configuration information has no hierarchical structure, and the full name of the configuration must be written
5. When the program loads the pro file through the IO stream, the default character set encoding IS0-8859-1
YML configuration file description
#About YML configuration file description # 1. Data structure key=value # 2. Data types are strings by default. If type conversion is required, the framework has already completed it internally # 3.yml writing: 1.key: (space ) value 2. There is a hierarchical structure, pay attention when editing # 4. Character set encoding: The default program loading is UTF-8 server: port: 8080 #project release path servlet: # /default localhost:8080/jt/xxxx request path context-path: /
SpringBoot assign s a property
Business description
Note: because the business needs some attribute information, if it is written directly in the code, the later of expansion is not good, so dynamic assignment is required. Since objects are generally managed by Spring container, the assign of operation should also have Spring container assign ment
Edit the YML configuration file
server: port: 8080 # project release path server: # / default localhost:8080/jt/xxxx request path context-path: / # 2. Assign the attribute hello to represent the prefix key=hello.msg hello: msg: "Hello SpringBoot"
assign a value to a property
@RestController //Returns a specially formatted string of JSON to the front end public class HelloController{ //Requirement: get attribute data from container springel=spel expression @Value("${hello.msg }") //Automatically generate get/set methods private String msg ; // = "Hello SpringBoot" }
hot deployment
explain
Note: Hot deployment is generally more applicable in the development phase, but this function is generally canceled in 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 restarts after 3~5 seconds
Add hot deployment jar package
CV import in the project's pom.xml file
<!--Support hot deployment --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> </dependency>
Modify IDEA configuration
Description: In order to allow IDEA to automatically hot deploy
Key combination: ctrl + alt + shift + /
[External link image transfer failed, the source site may have an anti-leech mechanism, it is recommended to save the image and upload it directly (img-6jUmuCZp-1622595282808)(C:\Users\MTA\AppData\Roaming\Typora\typora-user-images\ image-20210527114331281.png)]
[External link image transfer failed, the source site may have an anti-leech mechanism, it is recommended to save the image and upload it directly (img-1qnAvIqk-1622595282811)(C:\Users\MTA\Desktop...png)]
Lombok bag
Annotated automatic generation of Get, Set, toString
<!-- Annotated automatic generation Get,Set,toString similar method --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency>
Self-annotated meaning:
@Data is written on the specified class to automatically generate get, set, toString and other methods for the specified class
@Accessors(chain = true) enable chain loading
@NoArgsConstructor No-argument constructor
@AllArgsConstructor full parameter constructor
import 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
Description: Sometimes an abnormal situation may occur when starting the computer, resulting in the mysql database service not starting normally, and the display effect indicates that the database connection is abnormal.
Check: Check if the MYSQL service item is available
Spring container
Explanation: Spring container = HashMap<k,v>
@Controller public class HelloController{ } // Instantiation: Reflection Mechanism
SpringBoot integrates MyBatis
Configure 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> <!--Support hot deployment --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> </dependency> <!-- Annotated automatic generation Get,Set,toString similar method --> <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 boot class
package com.jt; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class SpringBootRun { public stat ic v oid 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 module and enter the following code
server: port: 8090 #8090 is the new port number that can be specified by yourself
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
[External link image transfer failed, the source site may have anti-leech mechanism, it is recommended to save the image and upload it directly (img-fACNIsat-1622595282813)(C:\Users\MTA\AppData\Roaming\Typora\typora-user-images\ image-20210527151923310.png)]
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 (temporarily)
<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 import data source information
server: port: 8090 servlet: context-path: /spring: datasource: driver-class-name: com.mysql.jdbc.Driver url: jdbc :mys ql://127.0.0.1:3306/jtdb? Servertimezone=gmt%2b8&useunicode=true&characterencoding=utf8&autoreconnect=true&allowmultiqueries=true username: root \ pojo mapper-locations: classpath:/mybatis/mappers/*. XML # enable hump mapping configuration: Map underscore to camel case: true
About Mybatis Summary
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;/** * Test JDBC * used to connect the java program with the database, the purpose is to operate the database through java code * @author Cloud */public class TestJdbc extends JDBCUtils{ public static void main(String[] args) {// //Normal method(); / /// SQL injection attack solution method2(); //// JDBC connection SQL,java exercise method1()// Query Wu Yangyang of all data method3() in the user table// Insert data into dept table method4(); } private static void method4() { try { Class.forName("com.mysq l.jdb c.Driver"); Connecti on con = DriverManager.getConnect i on("jdbc : mysql : //localhost:3306 /jdbcte st","root","root"); String sql = "insert into dept(dname,loc) values(?,?)"; PreparedStatement ps = con.prepareStatement(sql ) ; ps .setString ( 1,"Sales Department"); ps.setString(2,"Second Area"); // Specially execute SQL ps.executeUpdate(sql); } catch (Cla ssNotFoundException | SQLException e) { e. prin tStac kT race ( ) ; } finally { try { ps .close(); } catch (SQLException throwables) { throwables.printStackTrace(); } try { con.close(); } catch (SQLException throwables) { throwa bles. pri ntS tac kT ace ( ) ; } } } pri va t e st atic voi d m et hod 3 ( ) { String g g g g [] s tr = { " jd b c :m y s q l: / / l o c a lho s t: 3 3 0 6 / j d bc t e s t " , " roo t ", " r o ot " } ; C onn ecti on c on n = JD BCUt ils .getConnection( str ) ; String [ ] pw1 = { "Wu Yangyang " , " 123456 " } ; String str1 = " select id , name e , pwd from user where e e name = ? and pwd = ? " ; JDBCUtils . getPreparedStatement ( str1 , pw1 ) ) ; } / * * * Use JDBC to query the user table of data in the data library through Java * / private static void method1() {try {/ / register the driver jar package class. Forname ("com. Mysql. JDBC. Driver"); / / connect to the data library connection con = drivermanager. Getconnection (/ / domain name: server name: / / data library of port number / data library name "jdbc: mysql://lo Calhost:3306 /jdbctest ", / / data library account data library password" ro OT "," root "); //get the transmitter state ent st = con.Cr EA tstatement(); //e xecute the SQL s state NT string SQL =" select id, name, p w d from us e r w here r e na me = ' Wu Y ng ya ng' a nd p wd = ' 123 4 56 ' " ; Resu ltSe t rs = s t.e e xe cute Que r y ( sql ) ) ) ) ; // Process | Parse the res ult set while e e ( rs . next( ) ) { String id = rs . getString ( 1 ) ; String g na me = rs . getString g g ( 2 ) ; String pwd = rs . getString ( 3 ) ; System . out . println ( id+ " \ n " + name+ " \ n " + pwd ) ) ) ; } // Release resources rs . close ( ) ; st . close ( ) ; con . close ( ) ; } catch ( ClassNotFoundException | SQLException e ) { e . printStackTrace ( ) ; } } / * * * use JDBC query user table of data * / private static void method ( ) { try { // 1 .Register the driver jar package Class.forName ( " com .mysql.jdbc.Driver " ) ; // 2 . Connect to the data library // getConnection ( 1 , 2 , 3 ) 1 is which data to connect to the library 2 is the username 3 is the password Connection con = DriverManager manage r.ge tC onnection( //Pro toc ol: server name ://data l ibrary of end s log an/dat a library name "jd bc: mysql ://localhost :3306/ jdbctest" , " root " , " root") ;/ / 3 . Get the transmitter Statement st = con.createStatement ( ); // 4. Exe cute e SQL String sql = " select ect id, nam e , pwd from user whe re na me = ' j ack ' and pwd = '123456'"; ResultSet rs = st.executeQuery(sql); // 5. Procedures sin g|par sing th e re sult set// tr AV erse all the numbers in the user table according to next() is used to determine if there is data.If there is no data, return 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);}a// 6 . Release resource rs . close ( ) ; st . close ( ) ; con . close ( ) ; } catch ( ClassNotFoundException | SQLException e ) { e. printStackTrace (); } } / * * * SQL injection attack of solution * Yes It mean s tha t when the e use r o n ly ente rs s d ata, the specia l of SQL * is i included , which results in only the name and no passwor d. You can an view all data * After the name is enter e d , Both value s w ill ca use SQL attack problems: jack ' # or jack' or '1 = 1 */public s tatic v oid method d d d2(){ Scanner sc = new Scanner(Syst e m .in ); //Solve SQL Injection Problems try { Class.forName("com.mysql.jdb c.Driver " ); String url = " jd bc : mysql : //l oca lho st : 330 6 / jdb cte st " ; String name = " roo t " ; String pwd = " root " ; Connection c on = DriverMan a g er .ge tC connecti o n ( url , name , p w d ) ; // here ? call alled placeholder Str in g sql = " select id , name , pwd from user where name = ? and pwd = ? " ; Prepare dStatement 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 g p wd1 = rs . ge tString(3 ) ; System . out . prin t l n( id + "\ t" + name 1 + " \t "+pw d 1 ); } // 6 . Release capital source rs.close( ); ps .close(); con.close(); } catch (ClassNotFoundException | SQLException e) { e.printStackTrace(); } // Expose SQL injection probl ems try { Class.forName( " com.mysql.jdbc.Driver "); String url = " jdbc :mysql: // localhost : 3306 / jdbct es t " ; String name = " root " ; String pw d = " roo t " ; con = Drive e rManager .get Connection( u rl , name, pwd ) ; State t s t = con.createStationionment ( ) ; System .out .pri ntl n ( " Plea se enter y ou r u s ern am e " ) ; St ring n = sc .next Line ( ) ; System . o ut .pr int ln ( " P le ase enter r y our password " ) ; String p = sc .nextLine ( ) ; String sql = " select id , name , pwd from user er wh ere name = '"+n+"'and pwd ='"+p+"'"; R resultSet rs = st .executeQuery (sql); while (rs.next()){ String id = rs .getString(1); String name1 = rs.ge tString(2); S tring pw d1 = rs.get String(3) ; System m m .out.print ln( i d+ "\t" + name1+ "\t" + pwd 1 ); } // 6. Release resou rce es s ou rc e rs .close( ) ; st .c l ose() ; con .close( ); } catch (Cla ssNotFoundException | SQLExc eption e ) { e.prin tStackTrace(); } } }
ORM idea
Object Relational Mapping (English: Object Relational Mapping, ORM for short, or O/RM, or O/R mapping), is a programming technology for implementing object oriented different programming languages type system of data conversion between. Effectively, it actually creates a Programming language The "virtual object database" used here. There are many free and paid ORM products available today, and some programmers prefer to create their own ORM tools.
Summary: Operate the database in an object-oriented way,
Difficulties: 1. Objects should form a one-to-one mapping with tables
2. The properties in the object should map one-to-one 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 #{attribute}
2. Query operation: handwritten SQL, the result set is automatically encapsulated
Thinking: Why has Mybatis not implemented a fully automated ORM for so many years? ? ?
Reason: Mybatis believes that the execution efficiency of SQL written by yourself is the highest, and it is also more general, such as multi-table association.
Summary: performance issues, if fully automated, object-oriented will affect performance
expand
Fully automated ORM
user object (…) userMapper.insert(user); the program is automatically stored in the library, the configuration is cumbersome