1. MybatisPlus
As always, the most important official documents are out first!
Official documents
1. Import dependency
<!--mysql--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.17</version> </dependency> <!--lombok--> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency> <!--mybatis plus--> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.0.5</version> </dependency>
2. Configuration yml file
spring: datasource: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/niit_test?characterEncoding=utf-8&serverTimezone=GMT username: root password: yts520..
Note the version of MySQL here.
3. Write corresponding layer code
3.1 User entity class
@Data @AllArgsConstructor @NoArgsConstructor public class User { private int id; private String username; private String pwd; private String url; }
3.2 dao
@Mapper public interface UserMapper extends BaseMapper<User> { }
Here we directly inherit BaseMapper. There are already basic and commonly used CRUD methods in it. We don't need to write them again.
3.3 startup
@MapperScan("com.niit.mybatisplus.dao")
Add the annotation MapperScan. Note that the scanning path cannot be wrong.
3.4 test
@SpringBootTest class MybatisplusApplicationTests { @Autowired private UserMapper userMapper; @Test void getUsers() { List<User> users = userMapper.selectList(null); users.forEach(System.out::println); } }
4. Configure log
Easy to view code
Add in the yml file:
#Log configuration mybatis-plus: configuration: log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
5. CRUD extension
5.1 insertion
class MybatisplusApplicationTests { @Autowired private UserMapper userMapper; //insert @Test public void insterUser(){ User user = new User(); user.setUsername("Yu Tiansong"); user.setPwd("123321"); user.setUrl("www.baidu.com"); user.setTencentcondition(1); int insert = userMapper.insert(user); System.out.println(insert); System.out.println(user); }
The ID is automatically generated
5.2 primary key generation strategy
Globally unique ID of distributed system:
Snowflake (snowflake algorithm) scheme
Primary key auto increment
- You need to add @ TableId(type = IdType.AUTO) to the entity class field
- The primary key id in the database must be self incremented
AUTO(0),NONE(1),INPUT(2),ID_WORKER(3),UUID(4),ID_WORKER_STR(5);
5.3 update
//Update @ test public void updateuser() {usermapper. Updatebyid (new user (3L, "peach");}
Mybatis plus automatically configures dynamic SQL.
5.4 automatic filling
Creation time and modification time! These operations are completed automatically. We don't want to update them manually!
Alibaba Development Manual: all database tables: gmt_create, gmt_modified almost all tables should be configured! And need automation!
Database (not recommended)
-
Add field create_time, update_time
Default CURRENT_TIMESTAMP
-
Add attributes to the corresponding entity class
code implementation
Add padding to fields
@TableField(fill = FieldFill.INSERT)private Date createTime;@TableField(fill = FieldFill.INSERT_UPDATE)private Date upDateTime;
5.5 optimistic lock and pessimistic lock
Optimistic lock:
As the name suggests, it is very optimistic. It always thinks that there will be no problems, so it won't lock it. If a problem occurs, update the test again.
Pessimistic lock: hence the name Siyi is very pessimistic. It always thinks that there is always a problem and it will lock no matter what it does! Do it again!
Test:
-
Add the optimistic lock version field to the database
-
The default is 1
-
Add the corresponding attribute in the entity class
-
Register components
@MapperScan("com.niit.mybatisplus.dao")@EnableTransactionManagement //Automatic management of things @ Configuration / / Configuration class public class MybatisPlusConfig {/ / register optimistic lock plug-in @ bean public optimizationlockerinterceptor optimizationlockerinceptor() {return new optimizationlockerinceptor();}}
UPDATE user SET username=?, pwd=?, url=?, tencentcondition=?, version=?, create_time=?, update_time=? WHERE id=? AND version=?
-
test
//Optimistic lock - success case @ test public void versiondemo() {user user = usermapper.selectbyid (4); user.setusername ("optimistic lock test 2"); usermapper.updatebyid (user);}
//Optimistic lock - failure case @ test public void versiondemo2() {/ / normal thread user user = usermapper.selectbyid (4); user.setusername ("optimistic lock test - normal"); / / queue cutting thread user user2 = usermapper.selectbyid (4); user2.setusername ("optimistic lock test - queue cutting"); userMapper.updateById(user2); userMapper.updateById(user);// If there is no optimistic lock, the updated value of queue jumping thread lock will be overwritten}
[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-pscxweav-1629779125953) (C: \ users \ 55334 \ appdata \ roaming \ typora user images \ image-20210822162418613. PNG)]
5.6 query
//Query @ test void getusers() {list < user > users = usermapper. Selectlist (null); users. Foreach (system. Out:: println);}
Paging query:
[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-jnpbi7a8-1629779125955) (C: \ users \ 55334 \ appdata \ roaming \ typora \ typora user images \ image-20210822172125412. PNG)]
5.7 deletion
[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-fjoryicp-1629779125955) (C: \ users \ 55334 \ appdata \ roaming \ typora user images \ image-20210822172308928. PNG)]
[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-8gj9e5uk-1629779125957) (C: \ users \ 55334 \ appdata \ roaming \ typora \ user images \ image-20210822172412981. PNG)]
Logical deletion
Physical delete: delete directly from the database
Logical deletion: it is not deleted in the database, but invalidated by a variable!
Logical deletion prevents data loss, similar to putting it in the recycle bin of the computer.
How to use (steps from official documents):
# Step 1: configure com baomidou. mybatisplus. core. config. GlobalConfig$DbConfig
- Example: application yml
mybatis-plus: global-config: db-config: logic-delete-field: flag # Global logically deleted entity field name(since 3.3.0,Step 2 can be ignored after configuration) logic-delete-value: 1 # Logical deleted value(The default is 1) logic-not-delete-value: 0 # Logical undeleted value (0 by default)
# Step 2: add @ TableLogic annotation to the entity class field
@TableLogicprivate Integer deleted;
Execute delete statement
//Delete @ testvoid deleteuser() {usermapper. Deletebyid (4);}
You can see:
==> Preparing: UPDATE user SET deleted=1 WHERE id=? AND deleted=0
> Parameters: 4(Integer)
< Updates: 1
It essentially executes an update statement!!
The data in the database is not deleted, but the deleted value is updated. 1 indicates that it has been deleted logically!
Now let's execute the query statement to see if we can query the data with id 4:
You can see that there is no data with id 4 in the query result!
5.8 performance analysis plug-in
Slow sql encountered. MP also provides a method to stop the query beyond the set time.
Remember to configure the environment in SpringBoot as dev or test environment!
5.9 conditional constructor
official: https://mp.baomidou.com/guide/wrapper.html#abstractwrapper
6. Code generator
I haven't done it yet. It's updated separately
Many pictures were posted to the local text by QQ screenshots at that time, but now they can't be uploaded..... There is no language