在Spring Boot中整合MyBatis需要完成以下步驟:
1. 添加依賴:在`pom.xml`文件中添加MyBatis和數(shù)據(jù)庫驅動的依賴,例如MySQL或者其他數(shù)據(jù)庫的依賴。
org.mybatis.spring.boot mybatis-spring-boot-starter 2.2.0 mysql mysql-connector-java 8.0.26
2. 配置數(shù)據(jù)源:在`application.properties`(或`application.yml`)文件中配置數(shù)據(jù)庫連接信息。
# 數(shù)據(jù)庫連接配置 spring.datasource.url=jdbc:mysql://localhost:3306/dbname spring.datasource.username=username spring.datasource.password=password spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver # MyBatis 配置 mybatis.type-aliases-package=com.example.domain mybatis.mapper-locations=classpath:mapper/*.xml
3. 創(chuàng)建Mapper接口:創(chuàng)建一個Java接口,用于定義與數(shù)據(jù)庫交互的方法,可以使用注解或XML方式進行編寫。
@Repository public interface UserMapper { @Select("SELECT * FROM users") ListgetAllUsers(); // 其他數(shù)據(jù)庫操作方法... }
4. 創(chuàng)建Mapper XML文件(可選):如果你選擇使用XML方式編寫SQL語句,可以在`resources/mapper`目錄下創(chuàng)建對應的XML文件。
5. 創(chuàng)建Service和Controller:創(chuàng)建一個Service類來調用Mapper中定義的方法,并在Controller中使用該Service來處理業(yè)務邏輯。
@Service public class UserService { @Autowired private UserMapper userMapper; public ListgetAllUsers() { return userMapper.getAllUsers(); } // 其他業(yè)務方法... } @RestController @RequestMapping("/users") public class UserController { @Autowired private UserService userService; @GetMapping public List getAllUsers() { return userService.getAllUsers(); } // 其他接口方法... }
6. 運行應用程序:啟動Spring Boot應用程序,并訪問相應的API地址,以驗證MyBatis是否正確整合。
總結而言,整合MyBatis到Spring Boot中需要完成以下步驟:添加依賴、配置數(shù)據(jù)源、創(chuàng)建Mapper接口、創(chuàng)建Mapper XML文件(可選)、創(chuàng)建Service和Controller。