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接口來操作數據庫。