table of Contents
1. Preliminary preparation of the project--MyBaitsPlus
Configure the configuration information for connecting to the database in application.properties:
Druid database connection pool related dependencies
Configure the use of Druid connection pool in application.properties:
Add the @MapperScan annotation to configure the package where the interface file is located:
2. Preliminary preparation of the project--MyBatisPlusGenerator
2.1. Use MyBatisPlusGenerator to generate code
2.2. Test the code generated by MyBatisPlusGenerator
3. Preliminary preparation of the project-Spring Security
Scarecrow Project
1. Preliminary preparation of the project--MyBaitsPlus
MyBatisPlus is based on MyBatis. It can automatically generate regular data access, so that developers do not need to write those by themselves. Every table will have regular data access functions, such as inserting data, deleting data based on id, etc.
First create the database straw
:
CREATE DATABASE straw;
And use the database:
USE straw;
Then create a user data table to facilitate subsequent access to the data:
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(20) COMMENT '用户名',
`nickname` varchar(20) NULL COMMENT '昵称',
`password` char(68) NOT NULL COMMENT '密码',
`gender` int(1) COMMENT '性别',
`day_of_birth` date COMMENT '生日',
`phone` varchar(20) COMMENT '电话号码',
`class_id` int(11) COMMENT '所属班级id',
`created_time` datetime COMMENT '注册时间',
`enabled` int(1) COMMENT '账号是否可用,0-否,1-是',
`locked` int(1) COMMENT '账号是否锁定,0-否,1-是',
`type` int(1) COMMENT '0-学生,1-老师',
`self_introduction` varchar(255) COMMENT '自我介绍',
PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 ROW_FORMAT=DYNAMIC;
Create entity classUser
Next, create an entity class corresponding to the data table. In the blog-user module project, cn.tedu.blog.user
create a model
sub-package under the root package, and create an entity class in this sub-package User
:
package cn.tedu.blog.user.model;
import lombok.Data;
import java.time.LocalDate;
import java.time.LocalDateTime;
@Data
public class User {
private Integer id;
private String username;
private String nickname;
private String password;
private Integer gender;
private LocalDate dayOfBirth;
private String phone;
private Integer classId;
private LocalDateTime createdTime;
private Integer enabled;
private Integer locked;
private Integer type;
private String selfIntroduction;
}
Before using MyBatisPlus , the dependency of MyBatisPlus is required . Since the current case only demonstrates this effect, it is possible to add related dependencies to the parent project or blog-user submodule project:
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.3.2</version>
</dependency>
Add MySQL dependency:
At the same time, you also need to add a dependency on MySQL:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
Configure the configuration information for connecting to the database in application.properties :
Then, you need to configure the configuration information for connecting to the database in application.properties :
spring.datasource.url=jdbc:mysql://localhost:3306/straw?
useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
spring.datasource.username=root
spring.datasource.password=root
When the configuration is completed, it should be tested in time to ensure that the configuration of the database connection is correct:
@Autowired
DataSource dataSource;
@Test
void getConnection() throws SQLException {
Connection conn = dataSource.getConnection();
log.debug("conn > {}", conn);
}
Druid
Database connection pool related dependencies
If you need to use Druid
or other database connection pools, you need to add related dependencies first:
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.23</version>
</dependency>
TheDruid
connection pool is configured in application.properties :
Then configure the connection pool in application.propertiesDruid
:
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.druid.initial-size=2
spring.datasource.druid.max-active=5
Create UserMapper
interface
When you need to use MyBatisPlus, you should create a mapper
sub-package (not required) in the root package of the project , and create an UserMapper
interface under this sub-package . The interface needs to inherit from the BaseMapper
interface provided by MyBatisPlus . When inheriting, the generic type is the entity class Types of:
package cn.tedu.blog.user.mapper;
import cn.tedu.blog.user.model.User;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
@Repository
public interface UserMapper extends BaseMapper<User> {
}
Add a @MapperScan
comment to configure the package where the interface file is located:
Same as using MyBatis, you need to add @MapperScan
annotations in the configuration class to configure the package where the interface file is located:
package cn.tedu.blog.user;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("cn.tedu.blog.user.mapper")
public class BlogUserApplication {
public static void main(String[] args) {
SpringApplication.run(BlogUserApplication.class, args);
}
}
UserMapperTests
Test class
At this point, MyBaitsPlus can be used normally. BaseMapper
Many data access functions have been defined in the interface, and MyBatisPlus will automatically complete the SQL statements corresponding to these data access functions. If you do not need to customize other methods, you can use it directly. of!
Assuming that you need to insert new user data into the user table, you can directly use the BaseMapper
defined insert()
method.
In the blog-user module project src / test / java to create the next cn.tedu.blog.user.mapper.UserMapperTests
test class, write and execute unit tests:
package cn.tedu.blog.user.mapper;
import cn.tedu.blog.user.model.User;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
@Slf4j
public class UserMapperTests {
@Autowired
UserMapper mapper;
@Test
void insert() {
User user = new User();
user.setUsername("root");
user.setPassword("1234");
int rows = mapper.insert(user);
log.debug("rows={}", rows);
}
}
Regarding
@Autowired
the solution of using the default error report when assembling the persistence layer interface object in IDEA :
Use
@Resource
annotations instead ;The configured
@Autowired
annotation parameters arerequired=false
:@Autowired(required=false)
;Add a
@Repository
comment before the interface .
If you execute the above unit test directly, the following error will occur:
Caused by: org.apache.ibatis.reflection.ReflectionException:
Could not set property 'id' of 'class cn.tedu.blog.user.model.User'
with value '1282871589072584705' Cause: java.lang.IllegalArgumentException: argument type mismatch
因在插入数据时,MyBatisPlus会自动生成
Id value (such as in the above error message 1282871589072584705
), you need to explicitly add an @TableId
annotation before the attribute corresponding to the primary key in the entity class , and set the annotation attribute type
to IdType.AUTO
:
@Data
public class User {
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
// 忽略后续代码
}
然后,再次运行,即可正常插入数据。
In addition, you can see that the executed SQL statement and related information are output in the log during this run. The reason why these logs are displayed is because:
-
The MyBatis framework will output this information by default;
-
SLF4j
The dependencies that must be added to the project to ensure that MyBatis outputs logs; -
The SQL log output level of MyBatis is Debug, and the display level of the log must be set lower, for example, set to
trace
.
2. Preliminary preparation of the project--MyBatisPlusGenerator
2.1. Use MyBatisPlusGenerator to generate code
IDEA created in the straw
project, as a parent project, creating a tutorial, Lombok
, Spring Web
, MySQL
, MyBatis Framework
and created in which the straw-portal
sub-module project:
MyBatisPlus Generator is a code generator. After running it, you can directly generate a large number of code files (such as Java classes, interfaces, and XML files for configuring SQL), and then copy these files to the officially used project. You can save some basic creation process!
First of all, the related use of the code generator should be in a separate sub-module project to avoid intersection with other projects (do not use the code generator in a project that is officially used)! Therefore, continue straw
to create a sub-module project dedicated to the code generator in the parent project straw-generator
. The creation process is exactly the same as the general sub-module project:
Then, download the 2 files necessary to use the code generator through http://doc.canglaoshi.org/config/mybatis-plus-generator.zip (in the same compressed package):
The above two files CodeGenerator
are the executable files of the code generator. The required files can be generated by adjusting the configuration and executing them. They mapper.java.ftl
are the template files of the Java class/interface files that need to be generated.
First of all, in the straw-generator sub-module project, delete the test file in the original src folder (or not delete it, mainly because it is useless). Similarly, you can also change the startup class under src ( ) And configuration file deletion (also not used).StrawGeneratorApplication
application.properties
In the pom.xml of the straw-generator submodule project , add the necessary dependencies:
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.3.2</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-extension</artifactId>
<version>3.3.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
<version>2.3.1.RELEASE</version>
</dependency>
Then, CodeGenerator.java
copy the downloaded and decompressed files directly to the project cn.tedu.straw.generator
package, and open the folder to check the value of each global attribute, especially which database to connect to, and the user name and password to connect to the database, which must be kept with the MySQL you are currently using Unanimous! You must also check modelName
the value of the attribute, which represents the name of a certain submodule project of the current aggregate project. This value will act on the package name of the final generated class and interface file:
After confirming that it is correct, create the ftl folder under src/main/resources of the straw-generator submodule project , and copy the downloaded file to this folder:mapper.java.ftl
Then, go back to the CodeGenerator
class and set the last global property (the property used to configure the location of the template file) to "/ftl/mapper.java"
(corresponding to the location where the file is placed above).
2.2. Test the code generated by MyBatisPlusGenerator
First add related dependencies in the pom.xml of the straw parent project :Druid
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.23</version>
</dependency>
In the straw-portal project application.properties configuration:
server.port=8080
spring.datasource.url=jdbc:mysql://localhost:3306/straw?
useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.druid.initial-size=2
spring.datasource.druid.max-active=7
mybatis.mapper-locations=classpath:mapper/*.xml
logging.level.cn.tedu.straw.portal=trace
Add a comment on the startup class of the project and configure the location of the interface file:
@MapperScan("cn.tedu.straw.portal.mapper")
After all is completed, create a test class under src/test/java of the straw-portal submodule project to perform a simple functional test:cn.tedu.straw.portal.mapper.UserMapperTests
package cn.tedu.straw.portal.mapper;
import cn.tedu.straw.portal.model.User;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import javax.jws.soap.SOAPBinding;
import javax.sql.DataSource;
import java.io.Serializable;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
@SpringBootTest
@Slf4j
public class UserMapperTests {
@Autowired
DataSource dataSource;
@Autowired
UserMapper userMapper;
@Test
void contextLoads() {
log.debug("UserMapperTests.context");
}
@Test
void getConnection() throws SQLException {
Connection connection = dataSource.getConnection();
log.debug("connection > {}", connection);
}
@Test
void insert() {
User user = new User();
user.setUsername("plus");
user.setPassword("1234");
int rows = userMapper.insert(user);
log.debug("rows={}", rows);
}
@Test
void selectById() {
Integer id = 1;
User user = userMapper.selectById(id);
log.debug("user > {}", user);
}
@Test
void selectList() {
List<User> users = userMapper.selectList(null);
log.debug("count={}", users.size());
for (User user : users) {
log.debug("user > {}", user);
}
}
}
3. Preliminary preparation of the project-Spring Security
Spring Security is a security component provided by Spring, which is mainly used to identify and authenticate the user's identity in the project.
Before using Spring Security, you need to add dependencies, which can be checked directly when creating the SpringBoot project, or you can add it to the already created project:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
First of all, Spring Security can realize the encryption processing of the password! To create a configuration class in the straw-portal submodule project cn.tedu.straw.portal.security.SecurityConfig
, you need to add @Configuration
annotations, customize the method in the class, and return PasswordEncoder
the object to the Spring container. The BCryptPasswordEncoder
type of the object can use the type object:
package cn.tedu.straw.portal.security;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
@Configuration
public class SecurityConfig {
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
Then, create a test class under src/test/java to cn.tedu.straw.portal.SecurityTests
test encryption:
package cn.tedu.straw.portal;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.security.crypto.password.PasswordEncoder;
@SpringBootTest
@Slf4j
public class SecurityTests {
@Autowired
PasswordEncoder passwordEncoder;
@Test
void encode() {
String rawPassword = "123456";
String encodePassword = passwordEncoder.encode(rawPassword);
log.debug("raw password={}, encode password={}", rawPassword, encodePassword);
}
}