In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >
Share
Shulou(Shulou.com)06/01 Report--
Table of contents:
1. SpringBoot integrates MyBatis and MyBatisPlus
two。 Configure and run the code generation tool
3. Unit test the CRUD function of Service and Mapper
4. REST API calls the database read and write function.
5. Question and answer: does MyBatis Plus Generator generate entity without get/set function?
SpringBoot is the most widely used Java development framework, which is characterized by automatic configuration dependent modules. A series of starter scaffolding is easy to use, which fully embodies the principles of "out of the box" and "agreement is better than configuration".
MyBatis is a database persistence layer framework, using ORM architecture, mapping entities and databases, encapsulating JDBC, supporting customized SQL, stored procedures and high-level mapping, so that developers only need to pay attention to SQL statements and CRUD operations, and do not need to deal with complex processes such as driver loading, creating and managing connections.
MyBatis configures the operation to be executed by xml or annotation, and generates the SQL statement to be executed through Java object and SQL dynamic parameter mapping, and the MyBatis framework maps the result to Java object return after execution.
MyBatis Plus further enhances, simplifies development and improves efficiency for MyBatis. This article shares the integration method of MyBatis Plus and code generator, tests the functional unit of Service and Mpper, and encapsulates a test interface.
Code file
Functional essentials
SpringBoot integrates MyBatis, MyBatisPlus
Pom.xml
Introduce MyBatis and MyBatis Plus dependencies: mybatis-spring-boot-starter, mybatis-plus-boot-starter, mybatis-plus-generator
Application.yml
Configure the data source
Code generation tool
MyBatisPlusGenerator.java
MyBatis Plus provides an easy-to-use and efficient code generation tool to configure paths and package names.
Generate code files
Entity, mapper, service
Inherit the CRUD function encapsulated by the base class BaseMapper and IService
Unit testing
MapperTest.java, ServiceTest.java
Test CRUD operation
Function call
CheckController.java
Add REST interface / chk/db to test database read and write function
Project Code: https://github.com/jextop/StarterApi/
MyBatis-Plus official website: https://mybatis.plus/guide/
First, SpringBoot integrates MyBatis and MyBatisPlus
1. When you create a new SpringBoot project, check MyBatis and the MyBatis dependency is automatically added.
two。 Add MyBatis Plus and Generator dependencies to pom.xml. Note that when you run the code generation tool, you need a library of page templates, and the example uses freemarker.
Org.mybatis.spring.boot
Mybatis-spring-boot-starter
2.1.1
Com.baomidou
Mybatis-plus-boot-starter
3.3.0
Com.baomidou
Mybatis-plus-generator
3.3.0
Org.springframework.boot
Spring-boot-starter-freemarker
3. Configure the data source in application.yml:
Spring:
Datasource:
Driver-class-name: com.mysql.cj.jdbc.Driver
Url: jdbc:mysql://127.0.0.1:3306/starter?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true&serverTimezone=UTC
Username: root
Password: root
Second, configure and run code generation tools
1. MyBatisPlus provides a powerful code generation tool, AutoGenerator, to modify the file path and package name in the code: MyBatisPlusGenerator.java
two。 Note that StrategyConfig.setEntityLombokModel (), which defaults to the on mode and is recommended to be set to false, is used with caution because lombok has a high degree of code intrusion and relies on IDE plug-ins.
3. Run MyBatisPlusGenerator.main (), and the generator can be placed in a separate project.
4. Generate entity, mapper and service, inherit the CRUD function encapsulated by the base class BaseMapper and IService.
Third, unit test the CRUD function of Mapper and Service
CRUD is an acronym for create (Create), read (Retrieve), update (Update) and delete (Delete) database operations. LogServiceImpl implements IService interface and aggregates LogMapper function:
Test the read and write database capabilities of LogService:
@ SpringBootTest
Public class LogServiceTest {
@ Autowired
LogServiceImpl logService
@ Test
Public void testSave () {
Boolean ret = logService.save (new Log () {{)
SetSummary (String.format ("service:% s", new Date ()
})
LogUtil.info (ret)
Assertions.assertTrue (ret)
}
@ Test
Public void testList () {
List ret = logService.list (new QueryWrapper ()
.orderByDesc ("id")
.last (true, "limit 2")
);
Ret.forEach (LogUtil::info)
Assertions.assertFalse (ret.isEmpty ())
}
}
Fourth, the REST interface calls the database read and write function
1. Add RestController:CheckController.java
two。 Add REST interface / chk/db, call mapper to read and write database
@ GetMapping (value = "/ chk/db")
Public Object db (@ RequestAttribute (required = false) String ip) {
/ / Write a log to db
Log log = new Log () {{
SetSummary (String.format ("db_test_%s_%s_ Database", ip, new Date ())
}}
LogMapper.insert (log)
/ / Read log from db
Log ret = logMapper.selectOne (new QueryWrapper ()
.orderByDesc ("id")
.eq ("summary", log.getSummary ())
);
Integer count = logMapper.selectCount (null)
Return new HashMap () {{
Put ("chk", "db")
Put ("msg", log.getSummary ())
Put ("status", log.getSummary (). Equals (ret.getSummary ())
Put ("count", count)
}}
}
3. Example of Postman calling API
Fifth, question and answer: does MyBatis Plus Generator generate entity without get/set function?
When the code generator generates Entity, the policy configuration provides a lombok property that specifies whether to use lombok mode and how the property accessor is generated.
The code generator example provided by l MyBatis Plus turns on lombok mode:
The Entity generated by l contains the @ Data annotation, and the get/set function will be generated automatically.
@ Data
@ EqualsAndHashCode (callSuper = true)
@ Accessors (chain = true)
Public class Log extends BaseEntity {
Private static final long serialVersionUID = 1L
Private Integer ops
Private String summary
}
Because lombok has a high degree of code intrusion and relies on IDE plug-ins, when not using lombok, just set the property to turn it off: StrategyConfig.setEntityLombokModel (false)
L StrategyConfig defaults to turning off lombok mode
L set to false or delete this line of code, the generated Entity will generate the get/set function
Public class Auth extends BaseEntity {
Private static final long serialVersionUID = 1L
Private String name
Public String getName () {
Return name
}
Public void setName (String name) {
This.name = name
}
}
-
If you think this article is helpful to you, please click "like", the blogger will be grateful!
Jext technology community focuses on: software engineering practices, JIRA R & D management, distributed system architecture, software quality assurance.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.