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 configure XML files with MyBatis in SpringBoot integration

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

Share

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

This article focuses on "SpringBoot integration how to use MyBatis to configure XML files", interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to configure XML files with MyBatis in SpringBoot integration.

I. ORM framework

Object-relational mapping (Object Relational Mapping,ORM) pattern is a technology to solve the mismatch between object-oriented and relational databases. To put it simply, ORM automatically persists objects in a program to a relational database by using metadata that describes the mapping between objects and databases.

Why do I need ORM?

When you develop an application (without using Oamp R Mapping), you may write a lot of data access layer code to save, delete, read object information from the database, etc.; in DAL, you have written a lot of methods to read object data, change state objects and other tasks, but these codes are always repeated. ORM provides a solution to these problems and simplifies the operation of persisting objects in the program to a relational database.

The essence of ORM framework is to simplify the coding of operating database in programming. Up to now, there are basically only two most popular in the field of Java. One is Hibernate, which claims that you don't have to write a sentence of SQL, and the other is MyBatis, which is famous for dynamic SQL. Both have their own characteristics. When the enterprise system development can be used flexibly according to the demand, we will find an interesting phenomenon: most of the traditional enterprises like to use Hibernate, while the Internet industry usually uses MyBatis.

II. Introduction to MyBatis

MyBatis is a standard ORM framework, which is widely used in the development of enterprises. MyBatis was originally an open source project of Apache, iBatis,2010 year, which migrated from Apache Software Foundation to Google Code, and changed its name to MyBatis,2013 and moved to Github in November. From the migration history of MyBatis, we can also see the development history of source hosting platform. GitHub has become the largest open source software hosting platform in the world. I suggest you pay more attention to this world's largest same-sex social networking site.

MyBatis supports an excellent persistence layer framework for normal SQL queries, stored procedures, and advanced mapping. MyBatis eliminates almost all manual setting of JDBC code and parameters and retrieval encapsulation of the result set. MaBatis can use simple XML or annotations for configuration and raw mapping, mapping interfaces and Java's POJO (Plain Old Java Objects, plain Java objects) to records in the database.

1. Advantages of MyBatis

SQL is extracted uniformly, which is convenient for unified management and optimization.

SQL is decoupled from code, separating business logic from data access logic, making the design of the system clearer, easier to maintain and easier to unit test.

Provides mapping tags to support ORM field relationship mapping between objects and databases

Provide object-relational mapping tags to support object-relational component maintenance

Write dynamic SQL flexibly and support various conditions to generate different SQL dynamically

2. Shortcomings of MyBatis

It takes a lot of work to write SQL statements, especially when there are many fields and associated tables.

The SQL statement depends on the database, resulting in poor database portability.

3. Several important concepts of MyBatis

Mapper configuration can be implemented using XML-based Mapper configuration files, MyBatis annotations based on Java annotations, or even directly using API provided by MyBatis.

Mapper interface refers to a self-defined data operation interface, which is similar to the so-called DAO interface. In the early days, the Mapper interface required custom implementation, but now MyBatis automatically creates a dynamic proxy object for the Mapper interface. The method of Mapper interface usually has an one-to-one correspondence with select, insert, update, delete and other XML nodes in Mapper configuration files.

All Mapper statements in Executor,MyBatis are executed through Executor, and Executor is a core interface of MyBatis.

SqlSession, the key object of MyBatis, is the exclusive property of performing persistence operations. Similar to the Connection,SqlSession object in JDBC, which completely contains all the methods of performing SQL operations based on the database, its underlying layer encapsulates the JDBC connection, and the mapped SQL statements can be executed directly with SqlSession instances.

SqlSessionFactory, a key object of MyBatis, is a compiled memory mirror of a single database mapping relationship. An instance of the SqlSessionFactory object can be obtained through the SqlSessionFactoryBuilder object class, while the SqlSessionFactoryBuilder can be built from a XML configuration file or a pre-customized instance of Configuration.

4. The workflow of MyBatis is as follows:

First load the SQL mapping file for the Mapper configuration, or the relevant SQL content of the annotations.

Create a session factory, and MyBatis constructs a session factory (SqlSessionFactory) by reading the information from the configuration file.

Create a session. According to the session factory, MyBatis can use it to create a session object (SqlSession), which is an interface that contains methods for adding, deleting, modifying, and querying database operations.

Create an actuator. Because the session object itself cannot directly manipulate the database, it uses an interface called a database executor (Executor) to help it perform operations.

Encapsulates a SQL object. In this step, the executor encapsulates the SQL information to be processed into an object (MappedStatement), which includes SQL statements, input parameter mapping information (Java simple type, HashMap or POJO), and output result mapping information (Java simple type, HashMap, or POJO).

Operate the database. Once you have the executor and the SQL information encapsulation object, you will use them to access the database, and then return the operation result to end the process.

What is MyBatis-Spring-Boot-Starter

Mybatis-spring-boot-starter is a component package provided by MyBatis to help us quickly integrate Spring Boot. Using this component, we can do the following:

Build independent applications

Can be configured almost zero

Requires very little XML configuration

Mybatis-spring-boot-starter depends on MyBatis-Spring and Spring Boot. The latest version 1.3.2 requires more than MyBatis-Spring 1.3 and Spring Boot version 1.5 or above.

Note that mybatis-spring-boot-starter is the Starter officially developed by MyBatis, not the startup package developed by Spring Boot. In fact, MyBatis sees that the market usage of Spring Boot is very high, so it takes the initiative to develop a Starter package for integration, but this integration does solve a lot of problems and is much easier to use than before. Mybatis-spring-boot-starter mainly provides two solutions, one is the simplified configuration version of XML, and the other is to use annotations to solve all problems.

In the past, only XML configuration was used in MyBatis, but later annotations were widely used, and MyBatis also complied with the trend to provide annotation support, from which we can see that MyBatis has always followed the changes of mainstream technology to improve itself. Next, I'll show you how to use the XML version.

The XML version maintains the mapping file, and the use of the latest version is mainly reflected in the implementation layer that does not need to implement Dao, and the system will automatically find the corresponding SQL in the mapping file according to the method name.

4. MyBatis single data source operation

Initialization script

To facilitate the demonstration of the project, you need to create a users table in the test repository, as follows:

DROP TABLE IF EXISTS `users`; CREATE TABLE `users` (`id` bigint (20) NOT NULL AUTO_INCREMENT COMMENT 'primary key id', `userName` varchar (32) DEFAULT NULL COMMENT' username', `passWord` varchar (32) DEFAULT NULL COMMENT 'password', `user_ sex` varchar (32) DEFAULT NULL, `nick_ name` varchar (32) DEFAULT NULL, PRIMARY KEY (`id`) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8

Critical dependency package

Of course, any mode requires the introduction of mybatis-spring-boot-starter 's pom file first, and now the latest version is 1.3.2.

Org.mybatis.spring.boot mybatis-spring-boot-starter 1.3.2

Application configuration

Application.properties add related configuration

Mybatis.config-location=classpath:mybatis/mybatis-config.xmlmybatis.mapper-locations=classpath:mybatis/mapper/*.xmlmybatis.type-aliases-package=com.neo.modelspring.datasource.url=jdbc:mysql://localhost:3306/test?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=truespring.datasource.username=rootspring.datasource.password=rootspring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

Mybatis.config-location, configure mybatis-config.xml path, configure MyBatis basic properties in mybatis-config.xml

Mybatis.mapper-locations, configure the XML file path corresponding to Mapper

Mybatis.type-aliases-package, configuring the entity class package path in the project

Spring.datasource.*, data source configuration.

When Spring Boot starts, the data source is automatically injected into SqlSessionFactory, SqlSessionFactory is used to build SqlSessionFactory, and then automatically injected into Mapper. Finally, we can directly use Mapper.

Startup class

Add scan @ MapperScan,Spring Boot to the startup class to automatically load the Mapper under the package path when the Mapper package is started.

@ Spring BootApplication@MapperScan ("com.neo.mapper") public class Application {public static void main (String [] args) {SpringApplication.run (Application.class, args);}}

Or add the annotation @ Mapper directly to the Mapper class, and it is recommended to use the above, otherwise it will be troublesome to add an annotation to each mapper.

Sample demonstration

MyBatis Public Properties

Mybatis-config.xml mainly configures the commonly used typeAliases, sets type aliases, and sets a short name for the Java type. It is only related to XML configuration and exists only to reduce the redundancy of fully qualified names of classes.

ResultType= "Integer" / / or parameterType= "Long"

Add a mapping file for User

Here, in order to get closer to the working situation, the two fields of the class and the database fields are set to be inconsistent, one of which uses enumerations. There is a great advantage of using enumerations. The data inserted into this property is automatically checked, and an error is reported if it is not the contents of the enumeration.

SELECT * FROM users

The third step is to write specific SQL statements, such as:

Second, configure the corresponding relationship between the table structure and the class:

First, specify the Mapper class address of the corresponding file:

One feature of MyBatis XML is that it can reuse XML. For example, some of our common XML fragments can be extracted and referenced in other SQL. For example:

Id, userName, passWord, user_sex, nick_name SELECT FROM users

This example is that the table fields that need to be queried are defined above, and the following SQL is introduced using include to avoid writing too much repetitive configuration content.

The following are examples of commonly used additions, deletions, changes, and queries:

SELECT FROM users WHERE id = # {id} INSERT INTO users (userName,passWord,user_sex) VALUES (# {passWord}, # {userSex}) UPDATE users SET userName = # {userName}, passWord = # {passWord}, nick_name = # {nickName} WHERE id = # {id} DELETE FROM users WHERE id = # {id}

The above update SQL uses the if tag, which can produce dynamic SQL according to different conditions, which is the biggest feature of MyBatis.

Write code for the Dao layer

Public interface UserMapper {List getAll (); UserEntity getOne (Long id); void insert (UserEntity user); void update (UserEntity user); void delete (Long id);}

Note: the method name here needs to be the same as the id property in the XML configuration, otherwise there will be no method to correspond to the executed SQL.

Test use

According to the usual use of Spring, you can directly inject the corresponding Mapper.

@ Resourceprivate UserMapper userMapper

If you are using Idea, the comments in this section often say "could not autowire", but there is no problem with Eclipse. In fact, the code is correct, which is a false alarm by Idea. You can choose to lower the level of Autowired testing without prompting. Use the search function to find Autowiring for Bean Class in the File | Settings | Editor | Inspections option, and change the Severity level from error to warning.

Next, you can directly use userMapper for database operations.

@ Testpublic void testUser () {/ / add userMapper.insert (new User ("aa", "a123456", UserSexEnum.MAN)); / / delete int count=userMapper.delete (21); User user = userMapper.getOne (1l); user.setNickName ("smile"); / / modify userMapper.update (user); / / query List users = userMapper.getAll ();}

Paging query

Multi-conditional paging query is one of the most commonly used functions in practical work, and MyBatis is especially good at dealing with this kind of problems. In the actual work, the paging will be simply encapsulated to facilitate front-end use. In addition, in the use of the Web development specification, the parameters of the Web layer will pass parameters to the object with the suffix param, and the entity class ending with result encapsulates the returned data.

First, define a paged basic class (default is 3 records per page, which can be modified according to the parameters passed by the frontend):

Public class PageParam {private int beginLine; / / start line private Integer pageSize = 3; private Integer currentPage=0; / / current page / / getter setter omit public int getBeginLine () {return pageSize*currentPage;// automatically calculates the start line}}

The query condition parameter class of user inherits the paging basic class:

Public class UserParam extends PageParam {private String userName; private String userSex; / / getter setter ellipsis}

Next, configure the specific SQL, first extract the query conditions.

And userName = # {userName} and user_sex = # {userSex}

Get the paging information and query conditions from the object UserParam, and finally combine them.

Select from users where 1, 1 order by id desc limit # {beginLine}, # {pageSize}

The front end needs to show the total page number, so you need to count the total number of query results.

Select count (1) from users where 1

The two methods and configuration files defined in Mapper correspond to each other.

Public interface UserMapper {List getList (UserParam userParam); int getCount (UserParam userParam);}

Specific use:

@ Testpublic void testPage () {UserParam userParam=new UserParam (); userParam.setUserSex ("WOMAN"); userParam.setCurrentPage (1); List users=userMapper.getList (userParam); long count=userMapper.getCount (userParam); Page page = new Page (userParam,count,users); System.out.println (page);}

In practical use, you only need to pass in the CurrentPage parameter. The default 0 is the first page, and pass 1 is the content of the second page. Finally, the result is encapsulated as Page and returned to the front end.

Public class Page implements Serializable {private int currentPage = 0; / / current pages private long totalPage; / / total pages private long totalNumber; / / total records private List list; / / dataset}

Page encapsulates the paging information and data information to facilitate the front end to display the number of pages, total number and data, so the paging function is completed.

5. MyBatis multi-data source operation

Configuration file

First, we need to configure two different data sources. Note that the User table structure needs to be created in advance in the test1 and test2 libraries.

Mybatis.config-location=classpath:mybatis/mybatis-config.xmlspring.datasource.one.jdbc-url=jdbc:mysql://localhost:3306/test1?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=truespring.datasource.one.username=rootspring.datasource.one.password=rootspring.datasource.one.driver-class-name=com.mysql.cj.jdbc.Driverspring.datasource.two.jdbc-url=jdbc:mysql://localhost:3306/test2?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=truespring.datasource.two.username=rootspring.datasource.two.password=rootspring.datasource.two.driver-class-name=com.mysql.cj.jdbc.Driver

The first data source connects to the database test1 with the prefix spring.datasource.one.*, and the second data source connects to the database test2 with the prefix spring.datasource.two.*. The first data source connects to the database test1 with the prefix spring.datasource.one.*, and the second data source connects to the database test2 with the prefix spring.datasource.two.*.

Data source configuration

Create different Mapper package paths for the two data sources, copy the previous UserMapper to the package com.neo.mapper.one and com.neo.mapper.two paths, and rename them to User1Mapper and User2Mapper, respectively.

Configure the first data source, create a new DataSource1Config, and load the configured data source first

Bean (name = "oneDataSource") @ ConfigurationProperties (prefix = "spring.datasource.one") @ Primarypublic DataSource testDataSource () {return DataSourceBuilder.create () .build ();}

According to the created data source, build the corresponding SqlSessionFactory.

@ Bean (name = "oneSqlSessionFactory") @ Primarypublic SqlSessionFactory testSqlSessionFactory (@ Qualifier ("oneDataSource") DataSource dataSource) throws Exception {SqlSessionFactoryBean bean = new SqlSessionFactoryBean (); bean.setDataSource (dataSource); bean.setMapperLocations (new PathMatchingResourcePatternResolver (). GetResources ("classpath:mybatis/mapper/one/*.xml")); return bean.getObject ();}

The code needs to indicate the loaded Mapper xml file.

Add the data source to the transaction at the same time.

@ Bean (name = "oneTransactionManager") @ Primarypublic DataSourceTransactionManager testTransactionManager (@ Qualifier ("oneDataSource") DataSource dataSource) {return new DataSourceTransactionManager (dataSource);}

Next, inject the SqlSessionFactory created above to create the SqlSessionTemplate we need to use in Mapper.

@ Bean (name = "oneSqlSessionTemplate") @ Primarypublic SqlSessionTemplate testSqlSessionTemplate (@ Qualifier ("oneSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {return new SqlSessionTemplate (sqlSessionFactory);}

Finally, inject the SqlSessionTemplate created above into the corresponding Mapper package path, so that the Mapper under this package will use the first data source for database operations.

Configuration@MapperScan (basePackages = "com.neo.mapper.one", sqlSessionTemplateRef = "oneSqlSessionTemplate") public class OneDataSourceConfig {...}

BasePackages indicates the Mapper address.

SqlSessionTemplateRef specifies the sqlSessionTemplate injected under the Mapper path.

Second data source configuration

The configuration of DataSource2Config is similar to the above. In the method, you need to remove the @ Primary annotation and replace the corresponding data source and Mapper path. The following is a complete example of DataSource2Config:

@ Configuration@MapperScan (basePackages = "com.neo.mapper.two", sqlSessionTemplateRef = "twoSqlSessionTemplate") public class DataSource2Config {@ Bean (name = "twoDataSource") @ ConfigurationProperties (prefix = "spring.datasource.two") public DataSource testDataSource () {return DataSourceBuilder.create (). Build ();} @ Bean (name = "twoSqlSessionFactory") public SqlSessionFactory testSqlSessionFactory (@ Qualifier ("twoDataSource") DataSource dataSource) throws Exception {SqlSessionFactoryBean bean = new SqlSessionFactoryBean () Bean.setDataSource (dataSource); bean.setMapperLocations (new PathMatchingResourcePatternResolver (). GetResources ("classpath:mybatis/mapper/two/*.xml")); return bean.getObject ();} @ Bean (name = "twoTransactionManager") public DataSourceTransactionManager testTransactionManager (@ Qualifier ("twoDataSource") DataSource dataSource) {return new DataSourceTransactionManager (dataSource) } @ Bean (name = "twoSqlSessionTemplate") public SqlSessionTemplate testSqlSessionTemplate (@ Qualifier ("twoSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {return new SqlSessionTemplate (sqlSessionFactory);}}

We can sum up from the above steps that the process of creating multiple data sources is: first create DataSource, inject into SqlSessionFactory, then create transactions, inject SqlSessionFactory into the created SqlSessionTemplate, and finally inject SqlSessionTemplate into the corresponding Mapper package path. You need to specify the Mapper package path of the sub-library.

Note that in the case of multiple data sources, we do not need to add @ MapperScan ("com.xxx.mapper") annotations to the startup class.

In this way, the configuration of MyBatis multi-data sources is complete. If there are more data sources, please refer to the configuration of the second data source.

test

After configuring many data sources, you can inject the corresponding data source Mapper into the class to use which data source you want in the project.

RunWith (SpringRunner.class) @ SpringBootTestpublic class UserMapperTest {@ Autowired private User1Mapper user1Mapper; @ Autowired private User2Mapper user2Mapper; @ Testpublic void testInsert () throws Exception {user1Mapper.insert (new User ("aa111", "a123456", UserSexEnum.MAN)); user1Mapper.insert (new User ("bb111", "b123456", UserSexEnum.WOMAN)); user2Mapper.insert (new User ("cc222", "b123456", UserSexEnum.MAN));}}

The above test class injects two different Mapper corresponding to different data sources. Two pieces of data are inserted into the first data source, and a piece of information is inserted into the second data source. After running the test method, there are two pieces of data in database 1 and one piece of data in database 2, which proves that the multi-data source test is successful.

VI. Summary

This paper introduces the related concepts of ORM framework and MyBatis framework, and takes user data as an example to demonstrate the common scenarios such as MyBatis addition, deletion, modification, query, paging query, multi-data source processing and so on. Through the above example, we can find that MyBatis separates the execution SQL from the code, ensuring that the code processing and SQL are relatively independent, and the hierarchy is relatively clear. MyBatis is very friendly to dynamic SQL support, and dynamic SQL can be written efficiently by reusing code in XML files.

What is springboot? springboot is a new programming specification, which is designed to simplify the initial construction and development process of new Spring applications. SpringBoot is also a framework that serves the framework, and the scope of services is to simplify configuration files.

At this point, I believe that everyone has a deeper understanding of "SpringBoot integration how to use MyBatis configuration XML file", might as well come to the actual operation! Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

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