MyBatis与Spring Boot的集成非常简单,只需要在Spring Boot项目中添加MyBatis和相关依赖,然后配置MyBatis的数据源和Mapper扫描即可。
以下是一个简单的步骤:
1、在pom.xml中添加MyBatis和相关依赖:
```xml
```
2、配置数据源和MyBatis的Mapper扫描:
在application.properties或application.yml中添加数据库连接配置:
```properties
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接口:
```java
@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:
```java
@Mapper
public interface UserMapper {
User getUserById(Long id);
}
```
然后在resources目录下创建一个UserMapper.xml文件,定义SQL语句:
```xml
SELECT * FROM user WHERE id = #{id}
```
4、在Service或Controller中注入Mapper接口并使用:
```java
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public User getUserById(Long id) {
return userMapper.getUserById(id);
}
}
```
这样就完成了MyBatis与Spring Boot的集成,可以通过Mapper接口来操作数据库。