Beijing Taobao project day02

1.SpringBoot program enhancement

1.1 attribute assignment

Note: if the configuration information is written into the code in the form of code, the coupling of the program is high and it is inconvenient to expand
Requirement: whether the attribute of the object can be assigned dynamically

package com.jt.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController//Ensure that the returned data is converted into JSON
public class JDBCController {
	private String username;//Define database user name
	private String password;//Define database password
	
	@RequestMapping("/getMsg")
	public String getMessage() {
		this.username="root";
		this.password="root";
		return username+"|"+password;
	}

}

1.1.2@Value Mode assignment
1). Edit YML profile

# yml configuration file syntax
##  1. Key: value K-V structure is connected with: sign (space)
##  2. The YML configuration file has a hierarchical relationship
##  3. Pay attention to indentation in YML configuration file
##  4.YML files support Chinese The internal code is utf-8
server:
  port: 8090
  
  # Set project publishing path  
  servlet:
    context-path: /  
    # /Represents the default value directory  
    
# Add attributes and attribute values in the configuration file. In order to prevent duplicate names, prefix differentiation is added
jdbc:
  username: root
  password: root

2). Edit JDBCController to implement attribute assignment

@RestController //Ensure that the returned data is converted into JSON
public class JDBCController {
	
	//1. Requirements: use the information of YML configuration file to assign values to attributes
	//@Value function: find the specific key from the spring container and assign value to the attribute
	@Value("${jdbc.username}") //spel expressions are provided by spring
	private String username;	//Define database user name
	
	@Value("${jdbc.password}")
	private String password;	//Define database password
	
	@RequestMapping("/getMsg")
	public String getMsg() {
		
		this.username = "root";
		this.password = "root";
		return username+"|"+password;
	}
	
	@RequestMapping("/getMsgValue")
	public String getMsgValue() {
		
		return username+"|"+password;
	}
	
}

1.1.3 batch attribute assignment
1.1.3.1 business requirements
Sometimes some configurations may require a lot of attribute information. If @ Value attribute is used to assign Value at this time, there will be code redundancy and poor readability.
Solution: batch assignment is adopted

1.1.3.2 add jar package file
Attribute injection dependency:

<!--Add attribute injection-->
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-configuration-processor</artifactId>
	<optional>true</optional>
</dependency>

1.1.3.3 edit JdbcController2
Note the set/get method of the property

@RestController
@ConfigurationProperties(prefix = "jdbc")  //Defines the prefix of the attribute
public class JDBCController2 {

	//When assigning values to attributes in batch, the attributes in the configuration file must be consistent with the attribute names in the class Automatic assignment
	private String username;	//Define database user name
	private String password;	//Define database password
	
	//When assigning a value to an attribute, the set method of the object must be called
	
	@RequestMapping("/getMsgPrefix")
	public String getMsgValue() {
		
		return username+"|"+password;
	}
	
	
	

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}
	
}

1.2 assign a configuration file to assign a value to an attribute

1.2.1 business description
YML configuration file is the core file of SpringBoot program The important configuration of integrated environment is added If you need to assign business data sometimes The best way is to assign values in the form of properties (general!!!)
1.2.2 Edit pro configuration file
Pay attention to the encoding format: it is better to change it to utf-8



1.2.3 edit JDBC controller
Description: dynamically import pro configuration file

@RestController //Ensure that the returned data is converted into JSON
//properties establishes a relationship with the spring container. After specifying the pro file, load it The default loading policy adopts ISO-8859-1 encoding
//If it contains Chinese, it should be encoded in utf-8 format
@PropertySource(value = "classpath:/properties/jdbc.properties",encoding = "UTF-8")
public class JDBCController {
	
	//1. Requirements: use the information of YML configuration file to assign values to attributes
	//@Value function: find the specific key from the spring container and assign value to the attribute
	@Value("${jdbc2.username}") //spel expressions are provided by spring
	private String username;	//Define database user name
	
	@Value("${jdbc2.password}")
	private String password;	//Define database password
	
	@RequestMapping("/getMsg")
	public String getMsg() {
		
		this.username = "root";
		this.password = "root";
		return username+"|"+password;
	}
	
	@RequestMapping("/getMsgValue")
	public String getMsgValue() {
		
		return username+"|"+password;
	}
	
}

1.3 hot deployment configuration

Note: when the program is modified, the tomcat server can restart automatically
Just add the jar package file

<!--Support hot deployment -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
		</dependency>

1.4 environmental deployment

1.4.1 scenario
Xiao Zhang goes to work in the company, which is divided into test environment and production environment It needs to be run in the test environment during normal operation
The test environment requires port number 8080, user name = root, password root Wait
In the production environment, the port number is 80 and the user name is com tedu. Cn password tarena, etc
Xiao Zhang is in need of work You need to constantly switch between two environments
Question: how to simplify Xiao Zhang's operation?
1.4.2 solutions
Since there are multiple operating environments in the company, different operating environments will be planned In the future, the best way is to switch the name of the environment, and you can switch the real environment
1.4.3 edit YML configuration file

# Set default values for the environment
spring:
  profiles:
    active: test

---
# yml configuration file syntax
##  1. Key: value K-V structure is connected with: sign (space)
##  2. The YML configuration file has a hierarchical relationship
##  3. Pay attention to indentation in YML configuration file
##  4.YML files support Chinese The internal code is utf-8

#Define a name for the environment
spring:
  profiles: test  
  
server:
  port: 8080
  
  # Set project publishing path  
  servlet:
    context-path: /  
    # /Represents the default value directory  
    
# Add attributes and attribute values in the configuration file. In order to prevent duplicate names, prefix differentiation is added
jdbc:
  username: root
  password: root
  
#Separate configuration files
---
spring:
  profiles: prod  
    
server:
  port: 80
  
  # Set project publishing path  
  servlet:
    context-path: /  
    # /Represents the default value directory  
    
# Add attributes and attribute values in the configuration file. In order to prevent duplicate names, prefix differentiation is added
jdbc:
  username: com.tedu.cn
  password: tarena

Mblook.5 verification

1.5.1 add jar package file

<!--Introducing plug-ins lombok automatic set/get/Construction method plug-in  -->
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
</dependency>

1.5.2 installing LOMBOK plug-in
1). Locate lombok local disk location

2). Execute jar package file

3). install files

4). Verify LOMBOK plug-in

Common notes

1.5.4 about LOMBOK interview questions

Problem: set/get/toString and other methods can be added through lombok But you need to add lom plug-in in the running environment If the program is released in Linux system in the future Q: do you need to install lombok plug-in in advance

A. No need B need C don't know / it doesn't matter

Explanation: LOM plug-in takes effect at compile time The IDE tool will java files are compiled into class file, the lombok plug-in starts working For class file dynamic splicing get/set/toString and other methods So when the program runs in Linux xxxx.jar project (. class) file It can run directly It has nothing to do with whether lombok is installed or not

1.6 spring boot integrates Mybatis

1.6.1 new project

1). Create project

2). Add project name

1.6.2 add POM XML file

<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>
	<groupId>com.jt</groupId>
	<artifactId>springboot_demo_2</artifactId>
	<version>0.0.1-SNAPSHOT</version>

	<!--utilize parent label,springBoot The project integrates the packages and specific configurations of other frameworks parent Is defined in. Defines the version package information. -->
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.3.2.RELEASE</version>
		<relativePath /> <!-- lookup parent from repository -->
	</parent>

	<!--current maven configuration information -->
	<properties>
		<java.version>1.8</java.version>
		<!-- appoint maven Plug in version -->
		<maven-jar-plugin.version>3.1.1</maven-jar-plugin.version>
		<!-- Skip test class packaging -->
		<skipTests>true</skipTests>
	</properties>

	<!--Project dependency information. Maven: jar Package has dependencies A ~~~~ B ~~~~~C Import A Time BC Will be imported automatically. -->

	<dependencies>
		<dependency>
			<!--group ID:General company domain name inversion -->
			<groupId>org.springframework.boot</groupId>
			<!--entry name -->
			<!--SpringMVC Configuration information for jar Effect definition of configuration file out of the box -->
			<artifactId>spring-boot-starter-web</artifactId>
			<!--Project version number -->
			<!-- <version>Defined in parent</version> -->
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
			<exclusions>
				<exclusion>
					<groupId>org.junit.vintage</groupId>
					<artifactId>junit-vintage-engine</artifactId>
				</exclusion>
			</exclusions>
		</dependency>

		<!--Add attribute injection -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-configuration-processor</artifactId>
			<optional>true</optional>
		</dependency>

		<!--Support hot deployment -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
		</dependency>

		<!--Introducing plug-ins lombok automatic set/get/Construction method plug-in -->
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
		</dependency>

		<!--Introducing database driver -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<scope>runtime</scope>
		</dependency>

		<!--springBoot Database connection -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-jdbc</artifactId>
		</dependency>



		<!--spring integration mybatis temporary -->
		<dependency>
			<groupId>org.mybatis.spring.boot</groupId>
			<artifactId>mybatis-spring-boot-starter</artifactId>
			<version>1.3.2</version>
		</dependency>

	</dependencies>

	<!-- maven The plug-in configuration specified by the project is mainly responsible for maven Package project related operations/test/clean/update Other related maven Precautions for operation:But usually maven Items must be added 
		plug-in unit.Otherwise, the future project deployment will inevitably make mistakes -->
	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>
</project>

1.6.3YML configuration file

1). About data source configuration

spring:
  datasource:
    #driver-class-name: com.mysql.jdbc.Driver comments
    url: jdbc:mysql://127.0.0.1:3306/jtdb?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf8&autoReconnect=true&allowMultiQueries=true
    username: root
    password: root

Description of data source configuration:
serverTimezone=GMT%2B8 set time zone east zone% 2B ~+
&Useunicode = true & characterencoding = utf8 set encoding format
&Autoreconnect = true whether to reconnect if the link is disconnected
&Allowmultiqueries = true whether batch operations are allowed
2). About configuring Mybatis integration relationship

 mybatis:
  # Define alias package
  type-aliases-package: com.jt.demo.pojo
  # Batch import mapper mapping file
  mapper-locations: classpath:/mybatis/mappers/*.xml
  #Turn on hump mapping
  configuration:
    map-underscore-to-camel-case: true

3. Introduction to Mybatis configuration

<mapper namespace="com.jt.demo.mapper.UserMapper">
	
	<!--explain:If every database operation,All need to write pojo Package path for,The coding is cumbersome. 
		Optimization strategy:You can use alias packages instead.
		Question 1: If an alias package is used,Can I use the original path again. 
		answer:  It can be executed normally.   If there is a path, execute according to the path,If there is no path, it is executed according to the alias package.
			      If not,Error handling.
	 -->
	<select id="findAll" resultType="User">
		select * from user
	</select>
	
	<!--Description of hump rules
		map-underscore-to-camel-case: true  Enable hump rule mapping.
		
		surface:
		  field:   user_Id,user_age,user_sex
		
		object:
		  attribute:   userId,userAge,userSex
		
		If the above configuration,utilize restType When mapping,The assignment cannot be successful.
		
		Turn on hump mapping:
			user_id ~~~~~Remove intermediate"_"Line userid ~~~~~after"title case"userId(Case independent)
			The data is then mapped to the properties of the object.
			
		problem: 
			1.If hump rule mapping is enabled,Can the agreement be violated.
			For example, field information~user_id   | attribute~user_id    
			Can I map? Cannot map. But the program will not report an error.Just user_id The attribute of is null.
			
		conclusion: The hump mapping rule is enabled,Must be defined according to the rules.
	  -->
	
</mapper>

Omit @ mapper annotation

2. Introduction to mybatisplus

2.1MP introduction

MyBatis plus (MP for short) is an enhancement tool of MyBatis. On the basis of MyBatis, it only makes enhancement without change, and is born to simplify development and improve efficiency.

2.2 new features

No invasion: it is only enhanced without change, and its introduction will not affect the existing project, which is as smooth as silk
Low loss: the basic CRUD will be automatically injected upon startup, with basically no loss of performance and direct object-oriented operation
Powerful crud operation: built-in general Mapper and general Service. Most CRUD operations of a single table can be realized only through a small number of configurations. There is also a powerful condition constructor to meet various use needs
Support Lambda form call: through Lambda expression, it is convenient to write various query conditions without worrying about wrong fields
Support automatic generation of primary key: support up to 4 primary key strategies (including distributed unique ID generator - Sequence), which can be configured freely to perfectly solve the problem of primary key
Support ActiveRecord mode: support ActiveRecord formal calls. Entity classes only need to inherit Model classes to perform powerful CRUD operations
Support custom global general operations: support global general method injection (Write once, use anywhere)
Built in code generator: code or Maven plug-in can be used to quickly generate Mapper, Model, Service and Controller layer code, support template engine, and have more custom configurations for you to use
Built in paging plug-in: Based on MyBatis physical paging, developers do not need to care about specific operations. After configuring the plug-in, writing paging is equivalent to ordinary List query
The paging plug-in supports multiple databases: MySQL, MariaDB, Oracle, DB2, H2, HSQL, SQLite, Postgre, SQLServer and other databases
Built in performance analysis plug-in: it can output Sql statements and their execution time. It is recommended to enable this function during development and testing to quickly find out slow queries
Built in global interception plug-in: it provides intelligent analysis and blocking of full table delete and update operations, and can also customize interception rules to prevent misoperation

Wish: operate the database in an object-oriented way!!!

2.3 JPA thought

The Java Persistence API is used to map the object name of the Java Persistence API to the relational database of JPA.5, which is the Chinese name of the persistent object in the Java Persistence API. [1]
Sun introduced the new JPA ORM specification for two reasons: first, simplify the existing Java EE and Java SE application development; Second, sun hopes to integrate ORM technology to realize the unification of the world.

2.4 principle description of mybatisplus

Core: Operate the database as an object
Example: write usermapper Insert (user object);
Edit Sql by yourself
insert into user values(#{id},#{name},#{age}…); The future will be completed by the framework
reflection:
1. How are objects associated with tables? Realize object and table mapping through annotation
2. How to uniformly define curd operations? Encapsulate CRUD operations into Mapper interface Other mappers only need integration
3. The database can only recognize sql statements How to convert objects and sql???
Dynamically convert the operation of objects into sql statements Then hand it over to Mybatis for execution

	1. userMapper.insert(user object);
	 	 insert into user  values(#{id},#{name},#{age}....)

		2. deptMapper.insert(dept object);
		 insert into dept  values(.....)

2.5 importing jar package files

Note: after importing MP package, delete the original Mybatis package

<!--spring integration mybatis-plus -->
		<dependency>
			<groupId>com.baomidou</groupId>
			<artifactId>mybatis-plus-boot-starter</artifactId>
			<version>3.2.0</version>
	</dependency>

2.6 editing User POJO objects

2.7 inherit the public Mapper interface

2.8 modify YML configuration file

#Switch to Mybatisplus configuration   
mybatis-plus:
  # Define alias package
  type-aliases-package: com.jt.demo.pojo
  # Batch import mapper mapping file
  mapper-locations: classpath:/mybatis/mappers/*.xml
  #Turn on hump mapping
  configuration:
    map-underscore-to-camel-case: true

#Import sql log output
logging:
  level:
    com.jt.demo.mapper: debug 

2.9 introduction to mybatis

@SpringBootTest
public class TestMybatis {
	
	@Autowired
	private UserMapper userMapper;
	
	@Test
	public void testFindUser() {
		
		List<User> userList = userMapper.findAll();
		System.out.println(userList);
	}
	
	
	//1. Case 1: use MP to query all data
	@Test
	public void selectList() {
		
		List<User> userList = userMapper.selectList(null);
		System.out.println(userList);
	}
}

2.10 MP API learning

package com.jt.demo.test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import com.baomidou.mybatisplus.core.conditions.query.Query;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.jt.demo.mapper.UserMapper;
import com.jt.demo.pojo.User;

@SpringBootTest
public class TestMybatis {

	@Autowired
	private UserMapper userMapper;

	@Test
	public void testFindUser() {

		List<User> userList = userMapper.findAll();
		System.out.println(userList);
	}


	//1. Case 1: use MP to query all data
	@Test
	public void selectList() {

		List<User> userList = userMapper.selectList(null);
		System.out.println(userList);
	}


	//1. User warehousing
	//Note: during MP operation, the non null data in the object is regarded as the execution element
	@Test
	public void insert() {

		User user = new User();
		user.setName("Trump");
		user.setAge(60);
		user.setSex("male");
		userMapper.insert(user);
	}

	//1. Query users with name = "trump"
	//SELECT id,sex,name,age FROM user WHERE name=? 
	//You can only operate on the data of the business relationship No. =
	@Test
	public void select01() {
		//Define the condition constructor to dynamically splice the data after the where condition
		User user = new User();
		user.setName("Trump");

		//where name="xxxx"
		QueryWrapper<User> queryWrapper = new QueryWrapper<>(user);
		List<User> userList = userMapper.selectList(queryWrapper);
		System.out.println(userList);
	}

	//2. Query users with sex = "female" age > 200
	//Logical operators = EQ, > GT, < LT, > = Ge, < = le  
	@Test
	public void select02() {
		QueryWrapper<User> queryWrapper = new QueryWrapper<User>();
		queryWrapper.eq("sex", "female");
		queryWrapper.gt("age", 200);
		List<User> userList = userMapper.selectList(queryWrapper);
		System.out.println(userList);
	}

	/**
	 * 	3. Query the user like with "fine" in name
		sql: SELECT id,sex,name,age FROM user WHERE (name LIKE ?) 
		3.1 Query data ending with "fine" in name like% fine
		sql:SELECT id,sex,name,age FROM user WHERE (name LIKE ?) 
		    Parameters: %Fine (String)
	 */
	@Test
	public void select03() {
		QueryWrapper<User> queryWrapper = new QueryWrapper<User>();
		//queryWrapper.like("name", "fine");
		queryWrapper.likeLeft("name", "essence");
		List<User> userList = userMapper.selectList(queryWrapper);
		System.out.println(userList);
	}

	/**
	 * Case: the query age is 18-35 and requires gender "male"
	 * Rule: and connection is adopted by default under multi condition test
	 * SELECT id,sex,name,age FROM user WHERE (age BETWEEN ? AND ? AND sex = ?) 
	 */
	@Test
	public void select04() {
		QueryWrapper<User> queryWrapper = new QueryWrapper<User>();
		queryWrapper.between("age", 18, 35)
		.eq("sex", "male");
		List<User> userList = userMapper.selectList(queryWrapper);
		System.out.println(userList);
	}


	/**
	 * Requirement: query the user information whose name is not null,
	 * 		 And they are sorted in descending order by age. If the ages are the same, they are sorted by sex 
	 * 		 SELECT id,sex,name,age FROM user WHERE (name IS NOT NULL) ORDER BY age DESC , sex DESC 
	 */
	@Test
	public void select05() {

		QueryWrapper<User> queryWrapper = new QueryWrapper<User>();
		queryWrapper.isNotNull("name")
		.orderByDesc("age","sex");
		userMapper.selectList(queryWrapper);
	}

	//Query single user data
	@Test
	public void select06() {
		//1. Query according to the primary key to return a single object of value results
		User user = userMapper.selectById(1);
		System.out.println(user);

		//2. Query single data according to non primary key fields
		QueryWrapper<User> queryWrapper = new QueryWrapper<User>();
		queryWrapper.eq("name", "Trump");
		User user2 = userMapper.selectOne(queryWrapper);
		System.out.println(user2);

	}

	//Batch query data requires query id 1 3 5 8 10
	//SELECT id,sex,name,age FROM user WHERE id IN ( ? , ? , ? , ? ) 
	//in/or can be used for single table operation, but it should be used with caution for multi table operation
	@Test
	public void select07() {
		//1. idList encapsulates itself
		List<Integer> idList = new ArrayList<>();
		idList.add(1);
		idList.add(3);
		idList.add(5);
		idList.add(8);

		//2.Id information is generally transmitted by the front end, so it is generally in array format
		//Generally, when defining array format, it is best to use object type
		Integer[] ids = {1,3,5,8};
		//The array type needs to be converted to a collection
		List<Integer> list2 = Arrays.asList(ids);
		List<User> userList = userMapper.selectBatchIds(list2);
		System.out.println(userList);
	}

	//Total number of query records name is not null
	@Test
	public void select08() {

		QueryWrapper<User> queryWrapper = new QueryWrapper<>();
		queryWrapper.isNotNull("name");
		int count = userMapper.selectCount(queryWrapper);
		System.out.println(count);
	}

	//Practice deleting cases yourself
	@Test
	public void delete() {	
		
		userMapper.delete(null);
	}
	
	//Update database
	//Change the user information with id=53 to name = "Obama" age=66  
	@Test
	public void update01() {	
		//Update based on primary key The primary key information must be passed in the object
		User user = new User();
		user.setId(53).setName("Obama").setAge(66) ;
		userMapper.updateById(user);
	}
	
	//Change the user information name with name=null to = "test case" sex = "male" age=1;
	/**
	 * Parameters:
	 * 	1.entity  User assigned encapsulated object
	 *  2.Modified condition constructor
	 *  
	 * UPDATE user SET sex=?, name=?, age=? WHERE (name IS NULL) 
	 */
	@Test
	public void update02() {	
		
		User user = new User();
		user.setName("Test case").setAge(1).setSex("male");
		UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
		updateWrapper.isNull("name");
		userMapper.update(user, updateWrapper);
	}

}

Tags: Spring Boot architecture

Posted by tnewton on Sat, 21 May 2022 18:13:23 +0300