Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to integrate and use Spring Boot + Mybatis-Plus

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

How to integrate and use Spring Boot + Mybatis-Plus, I believe that many inexperienced people do not know what to do. Therefore, this paper summarizes the causes and solutions of the problem. Through this article, I hope you can solve this problem.

I. automatic configuration

When the SpringBoot application starts from the main method main (), first load the SpringBoot annotation class @ SpringBootApplication.

@ SpringBootApplicationpublic class DemoApplication {public static void main (String [] args) {SpringApplication.run (DemoApplication.class, args);}}

Load the annotation class @ EnableAutoConfiguration in this class.

Import the AutoConfigurationImportSelector autoconfiguration selector class in the EnableAutoConfiguration class using the annotation class @ Import to load other components that can be configured automatically, as follows:

1. The AutoConfigurationImportSelector automatic configuration selector calls the getCandidateConfigurations method, in which the SpringFactoriesLoader class scans the META-INF/spring.factories files under the classpath of each jar package through the loadFactoryNames method.

2. Encapsulate the scanned META-INF/spring.factories file into a Properties object

3. Traverse the Properties object and extract the value corresponding to the attribute name org.springframework.boot.autoconfigure.EnableAutoConfiguration.EnableAutoConfiguration. The value is the configuration class that the current Jar package needs to load with Spring Boot, loads it into the container, and instantiates the class object in the configuration class according to the configuration condition.

Protected List getCandidateConfigurations (AnnotationMetadata metadata, AnnotationAttributes attributes) {List configurations = SpringFactoriesLoader.loadFactoryNames (this.getSpringFactoriesLoaderFactoryClass (), this.getBeanClassLoader ()); Assert.notEmpty (configurations, "No auto configuration classes found in META-INF/spring.factories. If you are using a custom packaging, make sure that file is correct. "); return configurations;} private static Map loadSpringFactories (@ Nullable ClassLoader classLoader) {MultiValueMap result = (MultiValueMap) cache.get (classLoader); if (result! = null) {return result;} else {try {/ / scan META-INF/spring.factories file Enumeration urls = classLoader! = null? ClassLoader.getResources ("META-INF/spring.factories"): ClassLoader.getSystemResources ("META-INF/spring.factories"); LinkedMultiValueMap result = new LinkedMultiValueMap (); while (urls.hasMoreElements ()) {URL url = (URL) urls.nextElement (); UrlResource resource = new UrlResource (url) / / encapsulate the Properties object Properties properties = PropertiesLoaderUtils.loadProperties (resource) through the spring.factories file Url; Iterator var6 = properties.entrySet () .iterator (); while (var6.hasNext ()) {Entry entry = (Entry) var6.next () String factoryClassName = (String) entry.getKey (). Trim (); String [] var9 = StringUtils.commaDelimitedListToStringArray ((String) entry.getValue ()); int var10 = var9.length; for (int var11 = 0; var11)

< var10; ++var11) { String factoryName = var9[var11]; result.add(factoryClassName, factoryName.trim()); } } } cache.put(classLoader, result); return result; } catch (IOException var13) { throw new IllegalArgumentException("Unable to load factories from location [META-INF/spring.factories]", var13); } } } 来看下mybatis-plus-boot-starter包下的META-INF/spring.factories文件 文件中只有一条配置属性值,对应的自动配置类为MybatisPlusAutoConfiguration。至此,MyBatis-Plus是如何被自动配置并加载容器介绍到这里,后续会讲解Spring Boot时会更细致自动配置原理,各位同伴们继续关注。 org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.baomidou.mybatisplus.autoconfigure.MybatisPlusAutoConfiguration二、通用CRUD 了解Spring Boot是如何自动配置MyBatis-Plus后,接下来讲解使用MyBatis-Plus进行通用的CRUD操作以及相关操作的配置。 上一章节,我们准备了一个sql脚本,执行脚本后创建t_sys_log表,表结构可以查看上一章节。接着我们在项目中创建对应entity类和mapper接口 1. 目录结构如下

two。 The entity class SysLog attribute is as follows

Public class SysLog implements Serializable {private int logId; private Integer optionType; private String optionPerson; private String optionContent; private String optionIp; private String optionStatus; private String errorInfo; private Date optionTime; / / get and set method

3. Inherit the BaseMapper interface in the MyBatis-Plus package in the SysLogMapper interface, define the generic interface, and use the SysLog class

Import com.baomidou.mybatisplus.core.mapper.BaseMapper; public interface SysLogMapper extends BaseMapper {}

4. To inject the mapper interface, you need to instantiate the mapper into the Spring container, in these three ways

Add @ MapperScan ("com.banxun.demo.mapper") to the Spring Boot main method class, configure the package path where the mapper interface is located, and automatically scan the mapper interface under this path.

@ SpringBootApplication@MapperScan ("com.banxun.demo.mapper") public class DemoApplication {public static void main (String [] args) {SpringApplication.run (DemoApplication.class, args);}}

Add @ Mapper annotation directly to the mapper interface

Import com.baomidou.mybatisplus.core.mapper.BaseMapper;import org.apache.ibatis.annotations.Mapper; @ Mapperpublic interface SysLogMapper extends BaseMapper {}

Create a new config directory in the project, then create a new MybatisConfig configuration class, use the annotation @ Configuration to define this class as the configuration class, and use the annotation @ Bean. When the container starts, create a MapperScannerConfigurer object and set the basePackage attribute value to the package path of the mapper interface

Import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration; @ Configurationpublic class MybatisConfig {@ Bean public MapperScannerConfigurer MapperScannerConfigurer () {MapperScannerConfigurer scannerConfigurer = new MapperScannerConfigurer (); scannerConfigurer.setBasePackage ("com.banxun.demo.mapper"); return scannerConfigurer;}} III. Test generic CRUD

At this point, the basic configuration of MyBatis-Plus is complete, let's use junit to test, see if there are any problems with the test, and solve the specific problems. Other configurations of MyBatis-Plus are explained one by one in subsequent chapters.

1. Insert data

Inject SysLogMapper into the junit test class and write the following code to insert a log record to execute the junit test method

@ RunWith (SpringRunner.class) @ SpringBootTestpublic class BootApplicationTests {@ Autowired private SysLogMapper sysLogMapper; @ Testpublic void contextLoads () {SysLog sysLog = new SysLog (); sysLog.setOptionTime (new Date ()); sysLog.setOptionType (1); sysLog.setOptionContent ("Test mybatis-plus"); sysLogMapper.insert (sysLog);}}

Question 1: Error updating database. Cause: java.sql.SQLSyntaxErrorException: Table 'wechat.sys_log' doesn't exist

When the execution is completed, the console outputs and prints the above exception information, reporting that the sys_log table does not exist, while the table we created is named t_sys_log with the prefix "t _". In the current configuration, MyBatis-Plus automatically maps the hump structure class name to an underlined _ isolated table name by default. There are two ways to solve this problem:

Add @ TableName annotation to the entity class name SysLog to specify the mapping table name

@ TableName ("t_sys_log") public class SysLog implements Serializable {

Add the prefix "t _" when the configuration file application.properties adds global configuration attributes to unify the unannotated specified table name entity class mapping table name

Mybatis-plus.global-config.db-config.table-prefix=t_

Question 2: Cause: java.sql.SQLSyntaxErrorException: Unknown column 'log_id' in' field list'

According to question 1, the junit test method is executed again after the configuration is completed, and the console outputs and prints the above exception information, reporting that the log_id column does not exist. In the tdistribusys _ log table, the primary key is named f_log_id, and the field prefix is also missing. There are two solutions:

The default MyBatis-Plus automatically maps fields according to the attribute hump name and the primary key named id can specify the field name without comments.

The attribute name is annotated with @ TableField ("field name") to specify the mapping field name, and the primary key field is annotated with @ TableId ("field name").

Add global configuration attributes through the configuration file application.properties, and% s corresponds to automatically mapped field names.

Mybatis-plus.global-config.db-config.column-format=f_%s

Question 3:org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.reflection.ReflectionException: Could not set property 'logId' of' class com.banxun.demo.entity.SysLog' with value '1164549971505057794' Cause: java.lang.IllegalArgumentException: argument type mismatch

After configuring question 2, the console output prints the above exception information again. The reason for this problem is that the ID value generated by MyBatis-Plus for the primary key is too long when inserting data, and the primary key generation policy needs to be configured. There are also two ways to solve this problem:

Add @ TableId (value = "f_log_id", type = IdType.AUTO) to the primary key, IdType has six option values, default ID_WORKER, our table uses key values to automatically increment, so choose AUTO

Public enum IdType {AUTO (0), / / database self-increment NONE (1), / / stateless INPUT (2), / / self-input ID_WORKER (3), / / distributed global unique ID long integer type UUID (4), / / 32-bit UUID string ID_WORKER_STR (5); / / distributed global unique ID string type

Add global configuration attributes to the configuration file application.properties for unified processing

Mybatis-plus.global-config.db-config.id-type=auto

After the previous configuration, the junit method executes successfully and a log record is inserted into the library

2. Query data

Query according to id

@ Testpublic void contextLoads () {SysLog sysLog = sysLogMapper.selectById; System.out.println (sysLog.getOptionContent ());}

The console prints and inputs the previously inserted log content information

2019-08-22 23 com.zaxxer.hikari.HikariDataSource 16V 00.489 INFO 5112-[main] com.zaxxer.hikari.HikariDataSource: HikariPool-1-Start completed. _ _ | _ _ _ | (_ | | | _ | _ / | 3.1.2 2019-08-22 23 com.banxun.demo.DemoApplicationTests 00.867 INFO 5112-- [main] com.banxun.demo.DemoApplicationTests: Started DemoApplicationTests in 2.204 seconds (JVM running for 3.16) Test mybatis -plus2019-08-22 23 plus2019 16 Thread-2 01.132 INFO 5112-[Thread-2] com.zaxxer.hikari.HikariDataSource: HikariPool-1-Shutdown initiated...2019-08-22 23 16 plus2019 01.317 INFO 5112-[Thread-2] com.zaxxer.hikari.HikariDataSource: HikariPool-1-Shutdown completed.

Based on the content fuzzy query, this uses the QueryWrapper conditional constructor to do the conditional query

@ Testpublic void contextLoads () {QueryWrapper queryWrapper = new QueryWrapper (); queryWrapper.like ("f_option_content", "plus"); List sysLogs = sysLogMapper.selectList (queryWrapper); for (SysLog sysLog: sysLogs) {System.out.println (sysLog.getOptionContent ());}} 3. Update data @ Testpublic void contextLoads () {SysLog sysLog = new SysLog (); sysLog.setLogId (173) SysLog.setOptionContent ("Test Spring Boot + MyBatis-Plus"); sysLogMapper.updateById (sysLog);}

After the execution is completed, through the above query according to id, we can see that the console prints and inputs updated log content information.

2019-08-22 23 started by karanatarm in E 26 INFO 57.358 INFO 22964-[main] com.banxun.demo.DemoApplicationTests: Starting DemoApplicationTests on LAPTOP-6AQTBBR1 with PID 22964 (started by karanatarm in E:\ ideaplace\ demo) 2019-08-22 23 23 V 26 com.banxun.demo.DemoApplicationTests 57.359 INFO 22964-[main] com.banxun.demo.DemoApplicationTests: No active profile set Falling back to default profiles: default2019-08-22 23 INFO 26 main: 58.369 INFO 22964-[main] com.zaxxer.hikari.HikariDataSource: HikariPool-1-Starting...2019-08-22 23 23 Ride 26 Ride 58.813 INFO 22964-[main] com.zaxxer.hikari.HikariDataSource: HikariPool-1-Start completed. _ _ | _ _ _ | (_ | | | _ | _ / | 3.1.2 2019-08-22 23 com.banxun.demo.DemoApplicationTests 59.167 INFO 22964-[main] com.banxun.demo.DemoApplicationTests: Started DemoApplicationTests in 2.087 seconds (JVM running for 3.044) Test Spring Boot + MyBatis-Plus2019-08-22 23 Boot 26 INFO 59.456 INFO 22964-[Thread-2] com.zaxxer.hikari.HikariDataSource: HikariPool-1-Shutdown initiated...2019-08-22 23 23 INFO 26 Thread-2 59.518 INFO 22964-[Thread-2] com.zaxxer.hikari.HikariDataSource: HikariPool-1-Shutdown completed.4, Delete data @ Testpublic void tes () {SysLog sysLog = new SysLog () SysLog.setLogId; sysLogMapper.deleteById (sysLog);}

After the execution is completed, according to the id query, we can see that the console did not print the input log content.

After reading the above, have you mastered how to integrate and use Spring Boot + Mybatis-Plus? If you want to learn more skills or want to know more about it, you are welcome to follow the industry information channel, thank you for reading!

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.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report