What is the method of integrating and using MyBatis in …

The method of integrating and using MyBatis in Spring Boot is as follows:

Add dependencies: Add dependencies for MyBatis and the database driver in the pom.xml file.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

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

<!-- 添加数据库驱动依赖 -->
<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <scope>runtime</scope>
</dependency>

Create database configuration: Configure database connection information in the application.properties or application.yml file.

spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/mydatabase
spring.datasource.username=your-username
spring.datasource.password=your-password

Create entity class: Create a class that corresponds to the database table.

public class User {
    private Long id;
    private String name;
    // getter and setter
}

4. Create a Mapper interface: Create a Mapper interface for the corresponding database table, used to define SQL operations.

@Mapper
public interface UserMapper {
    @Select("SELECT * FROM user WHERE id = #{id}")
    User getUserById(Long id);
}

5. Create a Mapper XML file: In the resources directory, create an XML file with the same name as the Mapper interface, used to configure SQL statements.

<?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.mapper.UserMapper">
    <!-- 配置SQL语句 -->
    <select id="getUserById" resultType="com.example.model.User">
        SELECT * FROM user WHERE id = #{id}
    </select>
</mapper>

Inject the Mapper interface: Inject the Mapper interface in the Service or Controller and call its methods.

@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;

    public User getUserById(Long id) {
        return userMapper.getUserById(id);
    }
}

In this way, the integration of Spring Boot and MyBatis has been achieved, allowing the use of MyBatis for database operations.

bannerAds