Spring Boot 装配MyBatis Starter
时间: 2024-03-20 19:14:18 浏览: 68
要在Spring Boot项目中使用MyBatis Starter,需要先添加以下依赖项:
```xml
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.4</version>
</dependency>
```
然后,需要在application.properties文件中配置数据库连接信息:
```properties
spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true&useSSL=false
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
```
接下来,需要创建一个MyBatis映射器接口和一个相应的XML文件。例如,创建一个UserMapper接口和一个user.xml文件:
```java
public interface UserMapper {
@Select("SELECT * FROM user")
List<User> getAllUsers();
}
```
```xml
<mapper namespace="com.example.mapper.UserMapper">
<select id="getAllUsers" resultType="com.example.entity.User">
SELECT * FROM user
</select>
</mapper>
```
最后,需要在Spring Boot的应用程序类上添加@MapperScan注释,以扫描映射器接口:
```java
@SpringBootApplication
@MapperScan("com.example.mapper")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
```
现在,就可以在Spring Boot应用程序中使用MyBatis进行数据库操作了。例如,可以像下面这样使用UserMapper接口:
```java
@RestController
public class UserController {
@Autowired
private UserMapper userMapper;
@GetMapping("/users")
public List<User> getAllUsers() {
return userMapper.getAllUsers();
}
}
```
阅读全文