This article describes how SpringBoot integrates Mybatis (XML configuration).
1. What is MyBatis?
MyBatis is an excellent persistence layer framework that supports customization of SQL, stored procedures, and advanced mappings.MyBatis avoids almost all JDBC code and setting parameters manually and getting result sets.MyBatis can use simple XML or annotations to configure and map native types, interfaces, and Java POJO s (Plain Old Java Objects, plain old Java objects) as records in the database.
2. Integration Mode
SpringBoot also integrates Mybatis in two ways, XML configuration and annotation, with the following main advantages:
- Note: Code is simpler and more convenient.
- XML configuration: isolate SQL from business code and clearly express sql, especially for longer sql.
XML mapping files are also simple, with only a few top-level elements:
- cache - cache configuration for a given namespace.
- cache-ref - Reference to other namespace cache configurations.
- resultMap - The most complex and powerful element that describes how to load objects from a database result set.
- sql - A reusable statement block that can be referenced by other statements.
- Insert - Maps the insert statement.
- Update - Maps the update statement.
- Delete - Map delete statement.
- select - Maps the query statement.
This article describes how to configure XML, followed by comments.
3. Actual Warfare
Create a new spring boot project, spring-boot-mybatis-xml, and follow the steps below.
1. Introducing jar in pom.xml
The core of integrating MyBatis is relying on MyBatis-Spring-Boot-Starter, which provides:
- Automatically detect existing DataSource s.
- An instance of SqlSessionFactory that uses SqlSessionFactoryBean to pass the DataSource as input is created and registered.
- Instances of SqlSessionTemplate obtained from SqlSessionFactory will be created and registered.
- Automatically scan your mappers, link them to the SqlSessionTemplate, and register them in the Spring context to inject them into your bean s.
Important points of pom.xml are as follows:
<!-- mybatis-starter --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.1</version> </dependency> <!-- MySQL Connection Driven Dependency --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.39</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency>
2.application.yml Add Configuration
Add the configuration of the data source and mybatis to application.yml as follows:
spring: #data source datasource: 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
3. Add User's mapping file
UserMapper.xml is 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>
4. Add 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 is as follows:
public interface UserMapper { List<User> queryAllUsers(); }
5. Add Access Control Layer
The UserController code is as follows:
/** * UserController * * @Author: java_suisui * */ @Slf4j @RestController @RequestMapping("/user") public class UserController { @Autowired private UserService userService; /** * Query all users * */ @GetMapping("/queryAllUsers") public List<User> queryAllUsers(){ return userService.queryAllUsers(); } }
IV. Testing
Open your browser locally and visit http://localhost:8080/user/queryAllUsers. When successful, the following results are returned:
[{"id":1,"name":"Zhang San","password":"123456","sex":0,"des":"No Notes"}, {"id":2,"name":"Li Si","password":"123456","sex":0,"des":"No Notes"}]
By now, SpringBoot's ability to integrate Mybatis (XML Configuration Method) has been fully implemented. Please leave a message if you have any questions.
Full source address: https://github.com/suisui2019/springboot-study
Recommended reading
1. Print logs in Java, these 4 points are important!
2.SpringBoot Integrated JWT Implements Permission Authentication
3.One minute to learn about JWT certification!
4. How do you read yml profiles gracefully in SpringBoot?
5. How can SpringBoot be flexible in encrypting and decrypting interface data?
Free Java-related materials are available within a time limit, covering technologies such as Java, Redis, MongoDB, MySQL, Zookeeper, Spring Cloud, Dubbo/Kafka, Hadoop, Hbase, Flink, high concurrent distribution, big data, machine learning, etc.
Pay free attention to the following public numbers: