Integrate MyBatis in Spring Boot (xml-based & annotation-based implementation)

1. Prerequisites

When integrating MyBatis in Spring Boot, you need to import JDBC (no need to add it manually) and Druid's related dependencies.

  1. JDBC dependency: When integrating MyBatis in Spring Boot, there is no need to explicitly add JDBC package dependencies. This is because, when you added mybatis-spring-boot-starterthe dependency, it already included the dependency on JDBC. mybatis-spring-boot-starterIt is the official MyBatis dependency for integrating MyBatis and Spring Boot, which already includes support for JDBC . This dependency automatically imports the JDBC dependency for Spring Boot, so you don't need to add it manually

     SpringBoot integrates JDBC ---> SpringBoot integrates JDBC_Maiko Star's Blog-CSDN Blog

  2. Druid dependency: Druid is a powerful database connection pool and monitoring tool. If you want to use Druid as a connection pool, you need to import Druid dependencies. pom.xmlDruid dependencies can be added to the file in the following ways :

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid-spring-boot-starter</artifactId>
    <version>1.2.6</version>
</dependency>

SpringBoot integrates Druid ------>  SpringBoot integrates Druid_Maiko Star's Blog-CSDN Blog

2. Import MyBatis dependencies 

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.1.4</version>
</dependency>

Third, configure the database connection

Configure database connection information in application.propertiesor , for example:application.yml

spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=password
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

If you use Druid, you also need to add Druid-related configurations (spring.datasource.type=com.alibaba.druid.pool.DruidDataSource must be added, other configurations are not required)


# Druid配置
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.druid.initial-size=5
spring.datasource.druid.min-idle=5
spring.datasource.druid.max-active=20
spring.datasource.druid.test-on-borrow=false
spring.datasource.druid.test-while-idle=true
spring.datasource.druid.time-between-eviction-runs-millis=60000
spring.datasource.druid.min-evictable-idle-time-millis=30000
spring.datasource.druid.pool-prepared-statements=true
spring.datasource.druid.max-pool-prepared-statement-per-connection-size=20
spring.datasource.druid.filters=stat,wall,log4j
spring.datasource.druid.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000

4. Create a mapper folder under resources and configure the path in application.yml

image.png


The following is based on the xml method: 

 5. Write the corresponding xml file under the mapper file

<?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.dfrz.mapper.StudentMapper">

    <select id="getStuById" resultType="com.dfrz.pojo.Student">
        select * from `student` where id = #{id}
    </select>

</mapper>

6. Create the mapper package and the corresponding interface, add @Mapper annotation to the interface, or add @MapperScan(value = "com.dfrz.mapper") annotation to the startup class

Add the @Mapper annotation to the interface:

image.png

Add @MapperScan(value = "com.dfrz.mapper") annotation to the startup class:

image.png

 7. Test

Configure the corresponding controller for testing:

image.png

image.png

 Test success! ! !

8. You can add a configuration class to enable hump recognition

package com.dfrz.config;

import org.mybatis.spring.boot.autoconfigure.ConfigurationCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
    public class MybatisConfig {

        @Bean
        public ConfigurationCustomizer configurationCustomizer(){
            return new ConfigurationCustomizer() {
                @Override
                public void customize(org.apache.ibatis.session.Configuration configuration) {
                    configuration.setMapUnderscoreToCamelCase(true);//驼峰
                    //configuration.setCacheEnabled(true);//缓存
                }
            };
        }

    }

The following is based on the annotation method:

In MyBatis, you can use annotations to simplify the configuration of database operations. Through annotations, you can add corresponding annotations to the methods of the Mapper interface to specify the corresponding SQL statement and parameter mapping relationship, without writing XML Mapper files.

  1. @Select: An annotation used to perform query operations, specifying SQL query statements.

  2. @Insert: The annotation used to perform the insert operation, specifying the SQL insert statement.

  3. @Update: An annotation used to perform an update operation, specifying an SQL update statement.

  4. @Delete: Annotation for performing delete operations, specifying SQL delete statements.

 The following is an example of using annotations for database operations:

public interface UserMapper {

    @Select("SELECT * FROM users")
    List<User> getAllUsers();

    @Select("SELECT * FROM users WHERE id = #{id}")
    User getUserById(Long id);

    @Insert("INSERT INTO users(name, email) VALUES(#{name}, #{email})")
    @Options(useGeneratedKeys = true, keyProperty = "id") //用于在插入操作时生成主键并将生成的主键赋值给实体类的属性。
    int insertUser(User user);

    @Update("UPDATE users SET name = #{name}, email = #{email} WHERE id = #{id}")
    int updateUser(User user);

    @Delete("DELETE FROM users WHERE id = #{id}")
    int deleteUser(Long id);

}

Guess you like

Origin blog.csdn.net/weixin_55772633/article/details/131933037