GitHub: github.com/hsowan/soms
SOMS
Supermarket Orders Management System
Day 01
Use MyBatis
MyBatis official document
Refer: www.mybatis.org/mybatis-3/z…
Type the alias
Type aliases are your go-to. Using them, you don’t have to type the fully qualified name of the class. Such as:
<! --> <typeAlias type="com.someapp.model.User" alias="User"/> <! <select id="selectUsers" resultType="User"> select id, username, hashedPassword from some_table where id = #{id} </select>Copy the code
log4j2
Refer: logging.apache.org/log4j/2.x/m…
Eclipse for Mac shortcut
To delete a line
Command + D
Refer: www.cnblogs.com/TankXiao/p/…
Formatting code
Shift + Command + F
Day 02
MyBatis core configuration
Mybatis – config. The XML configuration
- Configuration
- Properties
- Settings
- typeAliases
- typeHandlers
- objectFactory
- Plugins
- Environments
- Environment (environment variable)
- transactionManager
- A dataSource
- Environment (environment variable)
- DatabaseIdProvider (Database vendor Identity)
- Mappers (mapper)
Refer: www.mybatis.org/mybatis-3/z…
Mapper. The XML configuration
- Insert – Mapping insert statements
- Update – Mapping update statement
- Delete – Mapping delete statement
- Select – Mapping query statement
- ResultMap – The most complex and powerful element describing how to load objects from a database result set.
- SQL – reusable block of statements that can be referenced by other statements.
- Cache – The cache configuration for a given namespace.
- Cache-ref – A reference to another namespace cache configuration.
Refer: www.mybatis.org/mybatis-3/z…
Create the SqlSessionFactory using the singleton pattern
/** * Main configuration file path */
private static String config = "mybatis-config.xml";
private static SqlSessionFactory sqlSessionFactory;
/** * Use singleton mode to get SqlSessionFactory *@return* /
private static synchronized SqlSessionFactory getSqlSessionFactory(a) {
if (sqlSessionFactory == null) {
try {
// Create an input stream to read the configuration file
InputStream is = Resources.getResourceAsStream(config);
// Create a SQLSession factory
sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
} catch (IOException e) {
// TODO Auto-generated catch blocke.printStackTrace(); }}return sqlSessionFactory;
}
Copy the code
Maven
Using JUnit
Add the following plug-in to pom.xml:
<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> < version > 3.0.0 - M3 < / version > < / plugin >Copy the code
Perform unit tests: MVN test
Refer: maven.apache.org/surefire/ma…
Skipping Tests
mvn install -DskipTests
Refer: maven.apache.org/surefire/ma…
JSP nine built-in objects + four domain objects
Refer: my.oschina.net/u/3805464/b…
Java’s eight basic types
byte/8
char/16
short/16
int/32
float/32
long/64
double/64
boolean/~
Copy the code
Day 03
Dynamic SQL
The official documentation
- if
- choose (when, otherwise)
- trim (where, set)
- foreach
- bind
www.mybatis.org/mybatis-3/z…
if
Rewrite UserMapper. XML:
<select id="listByUsername" resultMap="userResultMap">
select id, username, password
from user
where username like #{username}
<! - page - >
<if test="start ! = null and count ! = null">
limit #{start}, #{count}
</if>
</select>
Copy the code
Rewrite unit test testListByUsername(use map to pass parameters):
Map<String, Object> params = new HashMap<String, Object>();
params.put("username"."%user%");
List<User> users = session.selectList("com.ncucoder.mapper.UserMapper.listByUsername", params);
Copy the code
Execution Result:
==> Preparing: select id, username, password from user where username like ?
==> Parameters: %user%(String)
Copy the code
Add unit tests testListByUsernameUsingLimit:
Map<String, Object> params = new HashMap<String, Object>();
params.put("username"."%user%");
params.put("start".0);
params.put("count".2);
List<User> users = session.selectList("com.ncucoder.mapper.UserMapper.listByUsername", params);
Copy the code
Execution Result:
==> Preparing: select id, username, password from user where username like ? limit ?, ?
==> Parameters: %user%(String), 0(Integer), 2(Integer)
Copy the code
Bind fuzzy query
Modify UserMapper. XML:
<! Select * from user where username = 'username';
<select id="listByUsername" resultMap="userResultMap">
<bind name="username" value="'%' + _parameter.get('username') + '%'"/>
select id, username, password
from user
where username like #{username}
<if test="start ! = null and count ! = null">
limit #{start}, #{count}
</if>
</select>
Copy the code
Modify unit test testListByUsername():
Map<String, Object> params = new HashMap<String, Object>();
// params.put("username", "%user%");
params.put("username"."user");
List<User> users = session.selectList("com.ncucoder.mapper.UserMapper.listByUsername", params);
Copy the code
Execution Result:
==> Preparing: select id, username, password from user where username like ?
==> Parameters: %user%(String)
Copy the code
SQL optimization in
Query the records whose IDS are less than 5 in the user table
Query execution plan (QEP) using IN:
mysql> explain select id, username, password from user where id in (1.2.3.4.5);
+----+-------------+-------+------------+------+---------------+------+---------+------+------+----------+-------------+
| id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra |
+----+-------------+-------+------------+------+---------------+------+---------+------+------+----------+-------------+
| 1 | SIMPLE | user | NULL | ALL | PRIMARY | NULL | NULL | NULL | 10 | 50.00 | Using where |
+----+-------------+-------+------------+------+---------------+------+---------+------+------+----------+-------------+
1 row in set.1 warning (0.00 sec)
Copy the code
Use < QEP:
mysql> explain select id, username, password from user where id < 6;
+----+-------------+-------+------------+-------+---------------+---------+---------+------+------+----------+----------- --+
| id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra |
+----+-------------+-------+------------+-------+---------------+---------+---------+------+------+----------+----------- --+
| 1 | SIMPLE | user | NULL | range | PRIMARY | PRIMARY | 4 | NULL | 5 | 100.00 | Using where |
+----+-------------+-------+------------+-------+---------------+---------+---------+------+------+----------+----------- --+
1 row in set.1 warning (0.00 sec)
Copy the code
QEP with between:
mysql> explain select id, username, password from user where id between 1 and 5;
+----+-------------+-------+------------+-------+---------------+---------+---------+------+------+----------+----------- --+
| id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra |
+----+-------------+-------+------------+-------+---------------+---------+---------+------+------+----------+----------- --+
| 1 | SIMPLE | user | NULL | range | PRIMARY | PRIMARY | 4 | NULL | 5 | 100.00 | Using where |
+----+-------------+-------+------------+-------+---------------+---------+---------+------+------+----------+----------- --+
1 row in set.1 warning (0.00 sec)
Copy the code
type
Represents the method of accessing the table (best to worst: NULL > system > const > eq_ref > ref > range > index > All)key
saidMySQL Query Optimizer
frompossible_keys
The index selected for use inrows
saidMySQL Query Optimizer
The number of records in the result set estimated based on the statistics collected by the system is simply the number of records to be scanned
Analysis: When in is used as the query condition, full table scan (ALL) is performed without index; when < and between are used as the query condition, primary key index and index range scan are used. Therefore, the execution efficiency of IN is the lowest
MySQL batch insert test data
Gets a random string of specified length
drop function if exists `rand_string`;
create function `rand_string`(n int) returns varchar(255) charset 'utf8'
begin
DECLARE chars_str varchar(100) DEFAULT 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
DECLARE return_str varchar(255) DEFAULT ' ';
DECLARE i INT DEFAULT 0;
WHILE i < n DO
SET return_str = concat(return_str, substring(chars_str, FLOOR(1 + RAND() * 62), 1));
SET i = i + 1;
END WHILE;
RETURN return_str;
end;
Insert a specified number of users
drop procedure if exists `create_users`;
create procedure `create_users`(n int)
begin
declare i int default 0;
while (i < n) do
insert into user(username, password)
values (rand_string(10), rand_string(32));
set i = i + 1;
end while;
end;
Call the stored procedure
call create_users(1000);
Copy the code
Day 04
MyBatis Generator
The official documentation
www.mybatis.org/generator/c…
Question:
- Mysql > alter DATABASE MySQL8 alter database MySQL8 alter database MySQL8
Add dependencies and plug-ins
mybatis-generator-core:
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>${mybatis-generator.version}</version>
</dependency>
Copy the code
mybatis-generator-maven-plugin:
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>${mybatis-generator.version}</version>
<configuration>
<overwrite>true</overwrite>
<verbose>true</verbose>
</configuration>
</plugin>
Copy the code
Adding a Configuration File
- generatorConfig.xml
Generate the corresponding mapping file, entity class, and interface class
cd ${your_project}
mvn mybatis-generator:generator
Copy the code
Refer:
- www.cnblogs.com/hhhshct/p/9…
- Blog.csdn.net/liyonghong3…
Integration for SpringMVC
Add the dependent
<! -- Spring dependencies -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>${mybatis-spring.version}</version>
</dependency>
<! -- Druid connection pool -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>${druid.version}</version>
</dependency>
Copy the code
Modify theweb.xml
The configuration file
<! Create dispatcher -->
<servlet>
<servlet-name>soms-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/spring-*.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
<! -- Support asynchrony -->
<async-supported>true</async-supported>
</servlet>
<servlet-mapping>
<servlet-name>soms-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<! -- Chinese gibberish -->
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/ *</url-pattern>
</filter-mapping>
Copy the code
Add the Spring configuration file
- spring-web.xml
- spring-dao.xml
- spring-service.xml
Using MySQL8
Modify the dependent version (POM.xml):
<mysql-connector-java.version>8.0.16</mysql-connector-java.version>
Copy the code
Modify driver path (db.properties):
driver=com.mysql.cj.jdbc.Driver
Copy the code
Day 05
JWT + SpringSecurity
Github.com/hsowan/jwt-…