springboot如何集成mybatis
时间: 2023-04-22 19:03:24 浏览: 52
Spring Boot集成MyBatis的步骤如下:
1. 添加MyBatis和MyBatis-Spring依赖
在pom.xml文件中添加以下依赖:
```
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.4</version>
</dependency>
```
2. 配置数据源
在application.properties文件中配置数据源信息,例如:
```
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
```
3. 配置MyBatis
在application.properties文件中配置MyBatis信息,例如:
```
mybatis.mapper-locations=classpath:mapper/*.xml
mybatis.type-aliases-package=com.example.demo.entity
```
4. 创建Mapper接口和XML文件
创建Mapper接口和对应的XML文件,例如:
```
public interface UserMapper {
User selectUserById(Integer id);
}
```
```
<?xml version="1." encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.demo.mapper.UserMapper">
<select id="selectUserById" resultType="com.example.demo.entity.User">
select * from user where id = #{id}
</select>
</mapper>
```
5. 注册Mapper接口
在启动类中添加@MapperScan注解,例如:
```
@SpringBootApplication
@MapperScan("com.example.demo.mapper")
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
```
至此,Spring Boot集成MyBatis的配置就完成了。可以通过@Autowired注解注入Mapper接口,然后调用其中的方法来访问数据库。