MyBatis怎么与SpringBoot快速集成

2024-05-08,

MyBatis与Spring Boot的集成非常简单,只需要在Spring Boot项目中添加MyBatis和相关依赖,然后配置MyBatis的数据源和Mapper扫描即可。

以下是一个简单的步骤:

1、在pom.xml中添加MyBatis和相关依赖:

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.2.0</version>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.12.0</version>
</dependency>

2、配置数据源和MyBatis的Mapper扫描:

在application.properties或application.yml中添加数据库连接配置:

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

然后在Spring Boot的启动类上添加@MapperScan注解来扫描Mapper接口:

@SpringBootApplication
@MapperScan("com.example.mapper")
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

3、创建Mapper接口和对应的Mapper.xml文件:

创建一个Mapper接口,例如UserMapper.java:

@Mapper
public interface UserMapper {
    User getUserById(Long id);
}

然后在resources目录下创建一个UserMapper.xml文件,定义SQL语句:

<mapper namespace="com.example.mapper.UserMapper">
    <select id="getUserById" resultType="com.example.model.User">
        SELECT * FROM user WHERE id = #{id}
    </select>
</mapper>

4、在Service或Controller中注入Mapper接口并使用:

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

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

这样就完成了MyBatis与Spring Boot的集成,可以通过Mapper接口来操作数据库。

《MyBatis怎么与SpringBoot快速集成.doc》

下载本文的Word格式文档,以方便收藏与打印。