How to integrate MyBatis in Spring Boot?

To integrate Spring Boot with MyBatis, you can follow the steps below:

Step 1: Add dependencies for MyBatis and MyBatis-Spring-Boot-Starter in the pom.xml file.

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

Step 2: Configure database connection information and MyBatis properties.

Add the following configuration in the application.properties or application.yml file:

spring.datasource.url=jdbc:mysql://localhost:3306/db_example
spring.datasource.username=db_username
spring.datasource.password=db_password

mybatis.mapper-locations=classpath*:mapper/*.xml

Step 3: Create the Mapper interface and the corresponding XML file for MyBatis.

Create a Mapper interface, such as UserMapper.java, and write the Mapper methods.

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;

import java.util.List;

@Mapper
public interface UserMapper {

    @Select("select * from users")
    List<User> getAllUsers();
}

Create a UserMapper.xml file in the resources/mapper directory and configure the SQL statements.

<mapper namespace="com.example.mapper.UserMapper">

    <resultMap id="BaseResultMap" type="com.example.entity.User">
        <id column="id" property="id" />
        <result column="name" property="name" />
        <result column="email" property="email" />
    </resultMap>

    <select id="getAllUsers" resultMap="BaseResultMap">
        select * from users
    </select>
</mapper>

Step 4: Create Service and Controller.

Create a UserService interface and its corresponding implementation class, UserServiceImpl.

public interface UserService {

    List<User> getAllUsers();
}

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    public List<User> getAllUsers() {
        return userMapper.getAllUsers();
    }
}

@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/users")
    public List<User> getAllUsers() {
        return userService.getAllUsers();
    }
}

These are the basic steps to integrate Spring Boot with MyBatis. MyBatis will automatically scan Mapper interfaces based on configuration files and annotations during Spring Boot startup, generating proxy implementation classes. These Mapper interfaces can then be used to access the database.

bannerAds