After using mybatisplus, I haven't written SQL for a long time

Java fish 2021-09-15 06:58:42
using mybatisplus haven written sql


I heard that wechat search 《Java Young fish 》 It's going to change !

This article is included in github and gitee , There's my whole Java Series articles , Study or interview can see oh

( One ) Preface

First write JDBC When , To manually configure the connection information , Write one by one sql sentence . later Mybatis There is , There is no need to manually configure the connection information ,sql Statements are also isolated from code , But I have to write Sql. Then there was MybatisPlus, This next company Sql No need to write .

( Two ) What is? MybatisPlus

First, take out the official website address :

mp.baomidou.com/guide/

simply ,MybatisPlus yes Mybatis Enhanced tools for , Simplify the development , Improve development efficiency . In the website , He used such a picture to show MybatisPlus and Mybatis The relationship between .

In the picture ,MybatisPlus Indicates that it and Mybatis The relationship between them is like two brothers in a soul fight , They don't affect each other , But it can make it easier for you to fight monsters .

( 3、 ... and ) Lead to

In the interpretation of the MybatisPlus Before , Let's prepare a batch of data first

CREATE DATABASE user;
USE user;
SET NAMES utf8mb4;
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT ' user Id',
`username` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT ' user name ',
`password` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT ' password ',
`gmt_create` datetime(3) NOT NULL COMMENT ' Creation time ',
`gmt_modified` datetime(3) NOT NULL COMMENT ' Modification time ',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci;
INSERT INTO `user` VALUES
(1,'a001','name1','123456',now(),now()),
(2,'a002','name2','123456',now(),now()),
(3,'a003','name3','123456',now(),now()),
(4,'a004','name4','123456',now(),now()),
(5,'a005','name5','123456',now(),now()),
(6,'a006','name6','123456',now(),now()),
(7,'a007','name7','123456',now(),now()),
(8,'a008','name8','123456',now(),now()),
(9,'a009','name9','123456',now(),now()),
(10,'a010','name10','123456',now(),now())
 Copy code 

( Four )Mybatis Quick start

1、 Introduce the latest dependencies

<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>Latest Version</version>
</dependency>
 Copy code 

2、 Configure database connection information in the configuration center

spring.datasource.url=jdbc:mysql://192.168.61.102:3306/user?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=false
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
 Copy code 

3、 stay Spring Add in startup class MapperScan annotation

@SpringBootApplication
@MapperScan("com.example.mybatisplus.mapper")
public class MybatisPlusApplication {
public static void main(String[] args) {
SpringApplication.run(MybatisPlusApplication.class, args);
}
}
 Copy code 

4、 establish mapper,DO

MybatisPlus Can be generated automatically Mapper、DO、Service、Controller, Here's a tutorial , Manual establishment .MybatisPlus and Mybatis The first difference , Use here @TableName The annotation indicates which table the current entity class corresponds to

@Data
@TableName("user")
public class UserDO {
private Long id;
private String userId;
private String username;
private String password;
private LocalDateTime gmtCreate;
private LocalDateTime gmtModified;
}
 Copy code 

establish Mapper Class time , Inherit BaseMapper class , This is a MybatisPlus Provides a base class , Encapsulates common query operations

public interface UserMapper extends BaseMapper<UserDO> {
}
 Copy code 

5、 Query data

In the use of Mybatis when , Data CRUD All need to be written sql Can achieve ,MybatisPlus Provided BaseMapper Both provide Mapper Layer encapsulation interface , And provides Service Layer encapsulation interface . Based on the previous writing , In normal development, we tend to use Mapper The interface of the layer Introduce Mapper Several interfaces at the level :

For example, I want to inquire user The amount of data in the table , I can call :

Integer integer = userMapper.selectCount(null);
 Copy code 

MybatisPlus Provides a condition constructor Wrappers, Can pass Wrappers Construct a series of conditions , Such as query username by name1 The data of

List<UserDO> userDOList = userMapper.selectList(Wrappers.<UserDO>lambdaQuery()
.eq(UserDO::getUsername, "name1"));
 Copy code 

Another example is that I want to query id Greater than 5 The data of

List<UserDO> userDOList1 = userMapper.selectList(Wrappers.<UserDO>lambdaQuery()
.gt(UserDO::getId, 5));
 Copy code 

6、 Insert data into

There is no problem using the above method for data query , There are several things you can optimize when inserting data , We can use an annotation @TableId Set the auto increment method of the primary key , Can pass @TableField Annotation sets the automatic filling of data . So modify UserDO This class :

@Data
@TableName("user")
public class UserDO {
@TableId(type = IdType.AUTO)
private Long id;
private String userId;
private String username;
private String password;
@TableField(fill = FieldFill.INSERT)
private LocalDateTime gmtCreate;
@TableField(fill = FieldFill.INSERT_UPDATE)
private LocalDateTime gmtModified;
}
 Copy code 

In entity classes , Set up id Self increasing , Set up gmtCreate Auto fill on insert , Set up gmtModified Automatically fill in when creating and modifying , Then configure auto fill rules :

@Configuration
public class MybatisObjectHandler implements MetaObjectHandler {
@Override
public void insertFill(MetaObject metaObject) {
setFieldValByName("gmtCreate", LocalDateTime.now(),metaObject);
setFieldValByName("gmtModified", LocalDateTime.now(),metaObject);
}
@Override
public void updateFill(MetaObject metaObject) {
setFieldValByName("gmtModified",LocalDateTime.now(),metaObject);
}
}
 Copy code 

Finally, call API insert data

@Test
public void test3(){
UserDO userDO=new UserDO();
userDO.setUserId("a011");
userDO.setUsername("name11");
userDO.setPassword("123456");
userMapper.insert(userDO);
}
 Copy code 

For more query methods, please refer to the official website , Very detailed . But if yours sql The operation of connecting tables involving multiple tables , You can still talk to yourself MyBatis Same handwriting sql.

( 5、 ... and ) summary

thus , You should be right. MybatisPlus Have a general understanding of , Another thing worth mentioning MybatisPlus The open source organization Baomi bean is a domestic organization , Therefore, this document is particularly friendly to domestic developers , Safe to use . I'm a fish , See you next time !

版权声明
本文为[Java fish]所创,转载请带上原文链接,感谢
https://javamana.com/2021/09/20210909124112659r.html

  1. Opérateurs arithmétiques et opérateurs de comparaison pour JavaScript, Introduction classique au développement web
  2. MySQL + +: slow query log analysis (I)
  3. Explorer le cadre open source Android - 1. Okhttp Source Analysis
  4. 分布式宝典:限流 缓存 通讯,Java开发中常见的一些问题面试专题,
  5. 分享面试经历的网站,腾讯大牛教你自己写Java框架!
  6. Expliquer les six principes de base du modèle de conception par des exemples réels
  7. Site Web pour partager vos expériences d'entrevue, Tencent Bull vous apprend à écrire votre propre cadre Java!
  8. Dictionnaire distribué: communication de cache limitée par le courant, sujets d'entrevue pour certaines questions courantes dans le développement Java,
  9. Another uncle circle man is angry! The high-quality acting skills make people admire and achieve the highlight of the ending of spring in Jade House
  10. 10. MySQL database import, export and authorization
  11. 9. MySQL data query
  12. 8. MySQL data operation DML
  13. 7. MySQL database table engine and character set
  14. 分享面試經曆的網站,騰訊大牛教你自己寫Java框架!
  15. Les points de connaissance de Java Real - time Video Download, Byte Jumping Java R & D post ont été divulgués à l'intérieur.
  16. Introduction au JavaScript chapitre 15 (objets, clairvoyance)
  17. 前方高能,Java程序员最大的悲哀是什么?
  18. 别再说你不会JVM性能监控和调优了,2021华为Java高级面试题及答案,
  19. Tencent private cloud MySQL solution tdsql
  20. 前方高能,Java程序員最大的悲哀是什麼?
  21. Quelle est la plus grande tristesse des programmeurs Java à l'avenir?
  22. 15 useful cron work examples commonly used by Senior Linux system administrators
  23. Ne dites pas que vous ne pouvez pas surveiller et ajuster les performances JVM, 2021 Huawei Java Advanced interview Questions and Answers,
  24. 別再說你不會JVM性能監控和調優了,2021華為Java高級面試題及答案,
  25. 十多家大厂Java面试真题锦集干货整理,Java开发者该学习哪些东西提高竞争力?
  26. 十分钟带你回顾Spring常问的知识点,35岁老年程序员的绝地翻身之路,
  27. 区区一个SpringBoot问题就被干趴下了,看完这一篇就够了!
  28. K8s gestion des ressources (opérations de base)
  29. Java and cloud native dating
  30. 區區一個SpringBoot問題就被幹趴下了,看完這一篇就够了!
  31. Un problème de démarrage de printemps dans le district a été séché, et c'est assez!
  32. Dix minutes pour vous faire passer en revue les points de connaissance que Spring demande souvent, le chemin du retour Jedi d'un programmeur âgé de 35 ans,
  33. Plus d'une douzaine de grandes usines Java interview vrai sujet brocade collection de marchandises sèches, les développeurs Java devraient apprendre ce qui améliore la compétitivité?
  34. 十分鐘帶你回顧Spring常問的知識點,35歲老年程序員的絕地翻身之路,
  35. Guide de route d'apprentissage Java, redis a plusieurs types de données?
  36. 华为Java高级工程师面试题,字节跳动上千道精选面试题还不刷起来!
  37. 华为Java面试题目,腾讯Java开发面试记录,
  38. Propriétés et méthodes des objets Array en javascript!,Pseudo - classes et pseudo - éléments pour CSS
  39. Design pattern -- agent pattern
  40. 華為Java面試題目,騰訊Java開發面試記錄,
  41. Huawei Java interview title, Tencent Java Development interview record,
  42. Huawei Java Senior Engineer interview question, Byte Jumping thousand Selected Interview Question is still not Brushed!
  43. 双非本科字节跳动Java面试题分享,一篇文章教你搞定计算机网络面试,
  44. 又到一年金三银四,2021最新Java笔试题及答案,
  45. Huawei Finance and Economics 2021 Spring Recruitment interview, what is distributed Lock?Pourquoi utiliser des serrures distribuées?
  46. Un an plus tard, Golden, Silver, Silver, and Silver, 2021, the latest Java written Examination Questions and Answers,
  47. Partage de questions d'entrevue Java à double saut d'octets non - premier cycle, un article vous apprend à gérer l'entrevue réseau informatique,
  48. Computer graduation project java online voting system based on SSM
  49. K8s gestion des ressources (opérations de base)
  50. 又到一年金三銀四,2021最新Java筆試題及答案,
  51. Collection de code de base JavaScript (1)
  52. Vérification des permissions d'interface pour le démarrage du printemps à l'aide d'annotations personnalisées AOP +.
  53. Vérification des permissions d'interface pour le démarrage du printemps à l'aide d'annotations personnalisées AOP +.
  54. Cloud Security Daily 210914: Red Hat Jboss Middleware Platform found important Security Vulnerability and needs to be upgraded as soon as possible
  55. 吐血整理,腾讯团队实力打造spring入门教程,
  56. 史上最全的微服务专业术语面试50问,字节跳动Java岗经典面试真题,
  57. Absolument!C'est l'analyse la plus détaillée du code source de hashtap que j'ai jamais vu!
  58. Computer graduation project Java logistics order management system of logistics company based on SSM
  59. Talk about Kafka: source code analysis of producer
  60. [springboot2 starts from 0] development tips - Lombok, devtools, spring initailizr