This article introduces the SpringBoot integration Mybatis (XML configuration) process.

What is MyBatis?

MyBatis is an excellent persistence layer framework that supports customized SQL, stored procedures, and advanced mapping. MyBatis avoids almost all of the JDBC code and manual setting of parameters and fetching result sets. MyBatis can use simple XML or annotations to configure and map native types, interfaces, and Java’s Plain Old Java Objects (POJOs) to records in the database.

Second, integration method

SpringBoot also has two ways to integrate Mybatis, respectively XML configuration mode and annotation mode, the main advantages are as follows:

  1. Annotation method: the code is more concise and convenient.
  2. XML configuration: Isolate SQL from business code and express SQL cleanly, especially for long SQL.

The XML mapping file is also simple, with only a few top-level elements:

  • Cache – The cache configuration for a given namespace.
  • Cache-ref – A reference to another namespace cache configuration.
  • ResultMap – The most complex and powerful element describing how to load objects from a database result set.
  • SQL – reusable block of statements that can be referenced by other statements.
  • Insert – Mapping insert statements.
  • Update – Mapping update statement.
  • Delete – Mapping delete statement.
  • Select – Mapping query statement.

This article covers XML configuration, and a future article will cover annotations.

Third, in actual combat

To create a new Spring Boot project, spring-boot-mybatis-xml, follow these steps.

  1. Jar is introduced in pom.xml

The core of integrating MyBatis relies on MyBatis- Spring-boot-Starter, which provides:

  • Automatically detect existing DataSource.
  • An instance of SqlSessionFactory will be created and registered that uses the SqlSessionFactoryBean to pass the DataSource as input.
  • An instance of the SqlSessionTemplate obtained from the SqlSessionFactory will be created and registered.
  • Automatically scan your Mappers, link them to the SqlSessionTemplate and register them with the Spring context so they can be injected into your beans.

The important contents of POM.xml are as follows:

<! -- mybatis-starter --> <dependency> <groupId>org.mybatis.spring.boot</groupId> < artifactId > mybatis - spring - the boot - starter < / artifactId > < version > 2.1.1 < / version > < / dependency > <! --> <dependency> <groupId> MySQL </groupId> <artifactId>mysql-connector-java</artifactId> < version > 5.1.39 < / version > < / dependency > < the dependency > < groupId > org. Projectlombok < / groupId > <artifactId>lombok</artifactId> <optional>true</optional>
</dependency>
Copy the code
  1. Add configuration in application.yml

Add data source and mybatis configuration to application.yml as follows:

spring:
  # data sourcedatasource: url: jdbc:mysql://localhost:3306/demo? useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull
    username: root
    password: 123456
    driver-class-name: com.mysql.jdbc.Driver
# mybatis configuration
mybatis:
  typeAliasesPackage: com.example.springboot.mybatisxml.entity
  mapperLocations: classpath:mapper/*.xml
  config-location: classpath:mybatis-config.xml
Copy the code
  1. Add a mapping file for User

The contents of usermapper.xml are as follows:

<? xml version="1.0" encoding="UTF-8"? > <! DOCTYPE mapper PUBLIC"- / / mybatis.org//DTD Mapper / 3.0 / EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >

<mapper namespace= "com.example.springboot.mybatisxml.dao.mapper.UserMapper" >
    <resultMap id ="UserMap" type="com.example.springboot.mybatisxml.entity.User">
        <result column="id" property="id"/>
        <result column="name" property="name"/>
        <result column="sex" property="sex"/>
        <result column="password" property="password"/>
        <result column="des" property="des"/>
    </resultMap>

    <select id = "queryAllUsers" resultType= "com.example.springboot.mybatisxml.entity.User">
      select * from user
    </select>
</mapper>
Copy the code
  1. Adding a DAO Interface

The name of the interface is the same as the name of the mapping file, and the name of the method in the interface is the same as the ID of the label in the mapping file to be invoked.

The usermapper. Java code looks like this:

public interface UserMapper {

    List<User> queryAllUsers();
}
Copy the code
  1. Add an access control layer

The UserController code is as follows:

/**
 * UserController
 *
 * @Author: java_suisui
 *
 */
@Slf4j
@RestController
@RequestMapping("/user") public class UserController { @Autowired private UserService userService; /** */ @getMapping ("/queryAllUsers")
    public List<User> queryAllUsers() {returnuserService.queryAllUsers(); }}Copy the code

Four, test,

After the success of the local open a browser, visit http://localhost:8080/user/queryAllUsers, returned the following results:

[{"id": 1,"name":"Zhang"."password":"123456"."sex": 0."des":"No remarks"},
{"id": 2."name":"Bill"."password":"123456"."sex": 0."des":"No remarks"}]
Copy the code

To this SpringBoot integration Mybatis (XML configuration mode) function has been fully realized, welcome message communication!

Full source address: github.com/suisui2019/…

Recommended reading

1. Printing logs in Java, these four points are important!

2.SpringBoot integrates JWT to implement permission authentication

3. JWT Certification in a minute!

4. How to elegantly read yML configuration files in SpringBoot?

5. How to flexibly implement the encryption and decryption function of interface data in SpringBoot?


Limited time to receive free Java related materials, covering Java, Redis, MongoDB, MySQL, Zookeeper, Spring Cloud, Dubbo/Kafka, Hadoop, Hbase, Flink and other high concurrency distributed, big data, machine learning and other technologies. Follow the public account below to get free: