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 bind Mapper Interface to Sql by SpringBoot+Mybatis

2025-04-07 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article mainly shows you "SpringBoot+Mybatis how to achieve Mapper interface and Sql binding", the content is easy to understand, clear, hope to help you solve doubts, the following let Xiaobian lead you to study and learn "SpringBoot+Mybatis how to achieve Mapper interface and Sql binding" this article.

Usually when we use Mybatis for development, we will select the xml file to write the corresponding sql, then bind the Mapper interface to the xml file of sql, and then call the mapper interface in the project to execute the corresponding sql.

So how do you bind the Mapper interface to sql? This article will introduce four common postures.

Default policy

SpringBoot configuration parameter mybatis.mapper-locations

Designation

Specified by SqlSessionFactory

i. Environmental preparation

1. Database preparation

Use mysql as the example database of this article, and add a new table

CREATE TABLE `money` (`id` int (11) unsigned NOT NULL AUTO_INCREMENT, `name` varchar (20) NOT NULL DEFAULT''COMMENT' username', `money`int (26) NOT NULL DEFAULT'0' COMMENT 'money', `is_ deleted`tinyint (1) NOT NULL DEFAULT '0percent, `create_ at`timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT' creation time, `update_ at`update time', PRIMARY KEY (`id`), KEY `name` (`name`) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 two。 Project environment

This paper develops with the help of SpringBoot 2.2.1.RELEASE + maven 3.5.3 + IDEA.

Pom relies on the following

Org.mybatis.spring.boot mybatis-spring-boot-starter 2.2.0 mysql mysql-connector-java

Db configuration Information application.yml

Spring: datasource: url: jdbc:mysql://127.0.0.1:3306/story?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=Asia/Shanghai username: root password:II. Example demonstration

After setting up the environment, prepare the corresponding entity class and Mapper interface.

1. Entity class, Mapper interface

Database entity class: MoneyPo

@ Data@NoArgsConstructor@AllArgsConstructorpublic class MoneyPo {private Integer id; private String name; private Long money; private Integer isDeleted; private Timestamp createAt; private Timestamp updateAt;}

A basic Mapper interface

Mapperpublic interface MoneyMapper {trueint savePo (@ Param ("po") MoneyPo po);}

A demo service

@ Repositorypublic class MoneyRepository {private Random random = new Random (); public void testMapper () {MoneyPo po = new MoneyPo (); po.setName ("mybatis user"); po.setMoney ((long) random.nextInt (12343)); po.setIsDeleted (0); moneyMapper.savePo (po); System.out.println ("add record:" + po);} 2. Sql file

The contents of the xml file for writing sql are as follows

INSERT INTO `money` (`name`, `money`, `is_ deleted`) VALUEStrue (# {po.name}, # {po.money}, # {po.isDeleted}); 3. Mapper binds to Sql

The above are the basics of implementing CURD at the code level, which are basically the routines of mybatis operations, and there is nothing to pay special attention to; let's move on to the topic of this article.

How to tell mybatis to associate the above MoenyMapper interface with the xml file

3.1 default mode

Using the default binding method, there is no need for us to do additional operations, the point is that we need to follow the rules

The directory structure of xml, which is exactly the same as the package path of Mapper interface

The xml file name is exactly the same as the Mapper interface name (note that the case should be exactly the same)

Please note that the other one above is exactly the same

When binding using the default method, an example is shown above. Special attention should be paid to the case of file names, and the directory levels of xml files need to be exactly the same.

If you use the above method, there is still a problem during execution. The way to troubleshoot is to check whether the class file generated under the target directory is with the xml file, as shown below is a normal case.

Explain again

Based on the case above, we can directly write the xml file with the mapper interface without putting it under the resource path resources

3.2 SpringBoot configuration

SpringBoot provides a simple configuration to specify the binding between the Mapper interface and sql, which can be configured one line.

Mybatis: mapper-locations: classpath:sqlmapper/*.xml

It is relatively simple to use this method. It does not require the xml file to be the same as the Mapper interface file name, nor does it specify that the path level is the same.

3.3 Mapper tags

The mapper tag needs to be placed in the configuration file of mybatis, so we first specify the file path through the configuration parameters of SpringBoot.

Mybatis: configuration: config-location: classpath:mybatis-config.xml

Under the resource file, create a new file mybatis-config.xml

It is also feasible to specify the registration relationship through the mapper tag above. For details, please refer to the official documentation!

Https://mybatis.org/mybatis-3/configuration.html#mappers

3.4 SqlSessionFactory

In the previous blog post that introduced the registration of the Mapper interface, I introduced the registration through qlSessionFactory+ MapperScannerConfigurer

Here, you can also specify the xml file through SqlSessionFactory

@ Bean (name = "sqlSessionFactory") public SqlSessionFactory sqlSessionFactory (DataSource dataSource) throws Exception {SqlSessionFactoryBean bean = new SqlSessionFactoryBean (); bean.setDataSource (dataSource); bean.setMapperLocations (/ / sets the location of the xml of mybatis. Here mybatis annotation is used, and the xml file new PathMatchingResourcePatternResolver (). GetResources ("classpath*:mapping/*.xml") is not configured; / / register typehandler for global use of bean.setTypeHandlers (new Timestamp2LongHandler ()) Bean.setPlugins (new SqlStatInterceptor ()); return bean.getObject ();} 4. Summary

This paper mainly introduces four postures in which Mapper interfaces are bound to sql files, and understands the characteristics of several different postures. In the actual project development, you can choose one.

Default: under the resource resource directory, the directory level of the xml file is exactly the same as the package level of the Mapper interface, and the xml file name is the same as the mapper interface file name.

For example, mapper API: com.git.hui.boot.mybatis.mapper.MoneyMapper

Corresponding xml file: com/git/hui/boot/mybatis/mapper/MoneyMapper.xml

Springboot configuration parameters:

In the application.yml configuration file, specify mybatis.mapper-locations=classpath:sqlmapper/*.xml

Mybatis-config profile

This posture is common in non-SpringBoot project integration mybatis, and the relevant configuration of mybatis is usually placed in the mybatis-config.xml file.

First, in the configuration file, specify the load parameter mybatis.config-location=classpath:mybatis-config.xml

Then specify the mapper

Specified by SqlSessionFactory

You can specify the Mapper file directly in SqlSessionFactory

/ / set the xml location of mybatis. Mybatis annotation is used here, and the xml file bean.setMapperLocations (new PathMatchingResourcePatternResolver (). GetResources ("classpath*:mapping/*.xml") is not configured. The above is all the content of the article "how SpringBoot+Mybatis implements the binding of Mapper interface and Sql". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

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

Development

Wechat

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

12
Report