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 Mybatis-Plus in Spring Boot 2.x

2025-04-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

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

This article will explain in detail how to integrate Mybatis-Plus in Spring Boot 2.x. The content of the article is of high quality, so the editor shares it for you as a reference. I hope you will have a certain understanding of the relevant knowledge after reading this article.

The role of Mybatis-Plus

As you can see, it provides us with some core functions: code generators and off-the-shelf CRUD interfaces and conditional constructors that can be combined with Lambda make our code elegant enough, paging is also quite easy to use, and provide different primary key generation strategies. If these functions can not meet our needs, Mybatis-Plus also provides a wealth of plug-ins for us to use, we will only talk about the core functions, the use of plug-ins will be partially explained in the following article, interested students can first take a look at the official documentation.

Use the first step: introduce POM

First of all, we need to introduce POM, and I'm quoting the latest version here:

Next, if we need to use a code generator, we need to introduce the dependency of the template engine:

At this point, the introduction of pom is over, let's take a look at the writing of the configuration file:

Use step 2: write a configuration file

Here we use application.yml as the configuration file instead of the default application.properties for the new Spring Boot project. If you will not create a new Spring Boot project here, you can refer to the first article in this series of tutorials.

Here you can configure the print SQL so that we can troubleshoot the problem.

Use step 3: create a table

Use step 4: use the code generator

Post my code generator code directly:

Public class MpGenerator {public static void main (String [] args) {GlobalConfig config = new GlobalConfig (); String dbUrl = "jdbc:mysql://localhost:3306/viboot?useSSL=false"; DataSourceConfig dataSourceConfig = new DataSourceConfig () DataSourceConfig.setDbType (DbType.MYSQL) .setUrl (dbUrl) .setUsername ("root") .setPassword ("Passw0rd") .setDriverName ("com.mysql.cj.jdbc.Driver"); StrategyConfig strategyConfig = new StrategyConfig () StrategyConfig .setCapitalMode (true) / / is combined with Lombok, so it is set to true. If Lombok is not integrated, it can be set to false .setEntityLombokModel (true) .setNaming (NamingStrategy.underline_to_camel). / / since I am a multi-module project, I need to add the name of the submodule in order to generate it directly to this directory. If it is a single-module project, you can remove String projectPath = System.getProperty ("user.dir") + "/ viboot-mybatis-plus". / / Custom configuration InjectionConfig cfg = new InjectionConfig () {@ Override public void initMap () {}}; / / if the template engine is freemarker String templatePath = "/ templates/mapper.xml.ftl"; / / if the template engine is velocity / / String templatePath = "/ templates/mapper.xml.vm" / / Custom output configuration List focList = new ArrayList () / / Custom configuration will be outputted first focList.add (new FileOutConfig (templatePath) {@ Override public String outputFile (TableInfo tableInfo) {/ / Custom output filename return projectPath + "/ src/main/resources/mapper/" + "user" + "/" + tableInfo.getEntityName) () + "Mapper" + StringPool.DOT_XML }); cfg.setFileOutConfigList (focList) / / set the author, output path, whether to rewrite and other properties config.setActiveRecord (false) .setEnableCache (false) .setAuthor ("viyoung") .setOutputDir (projectPath + "/ src/main/java") .setFileOverride (true) .setServiceName ("% sService") New AutoGenerator () .setGlobalConfig (config) .setDataSource (dataSourceConfig) .setStrategy (strategyConfig) .setTemplateEngine (new FreemarkerTemplateEngine ()) .setCfg (cfg) / / set the package name here .setPackageInfo (new PackageConfig) () .setParent ("indi.viyoung.viboot.mybatis") .setController ("controller") .setEntity ("entity") .setMapper ("mapper") .setServiceImpl (" Service.impl ") .setService (" service ") .execute () }}

Let's run the main method and see the generated package:

Delete the xml package under the mapper package because we have generated the * mapper.xml file in resources. Note here that you need to configure MapperScan on the startup class of SpringBoot to help us find the location of the persistence layer interface.

Use step 4: write a query list for testing

Yes, we only need to write a line of code to get the list we want. Let's visit it.

IService and BaseMapper

Some people may wonder why we only need to call directly in the controller layer to get the list. This is because Mybatis-Plus encapsulates a series of basic interfaces for CRUD. The UserService interface generated by the code generator actually inherits the IService interface, while UserServiceImpl inherits ServiceImpl, so you can get some basic implementation.

IService provides us with the following ways to implement basic CRUD:

Similarly, the BaseMapper interface provides some implementations:

Through these basic implementations, we can complete most of the basic queries in daily life, and save the time of writing Service and ServiceImpl, which is better than JPA in terms of coding efficiency.

Conditional constructor

The condition constructor can construct some query conditions to get the value we specify, and can be used in conjunction with Lambda expressions. Let's write two examples directly:

As you can see, the part that has been commented out is written without using the Lambda expression, which has a magic value and will lead to errors due to careless misspelling of the name of column, but using the Lambda expression is intuitive enough to see that we want to query userName =? Next, let's run it to see if the result is as we expected.

Of course, there are many uses of conditional constructors, which are not listed here. Students in need can go to the official website to check the documents.

Paging query

If we need paging query data to render the table, we can use the paging plug-in that comes with Mybatis-Plus:

Add the above code to the startup class, and then we can use paging:

We just need to build a Page object, initialize the number of pages (page) and the amount of data per page (pageSize) we need, and then pass it as an argument to the page () method. Let's visit:

About Spring Boot 2.x how to integrate Mybatis-Plus to share here, I hope the above content can be of some help to you, can learn more knowledge. If you think the article is good, you can share it for more people to see.

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