springboot 集成mybaties 代码举例
时间: 2024-12-16 10:14:58 浏览: 12
Spring Boot集成MyBatis主要是通过第三方库如mybatis-spring-boot-starter来简化配置和整合。以下是一个简单的示例:
首先,在pom.xml文件中添加mybatis和spring-boot-mysql依赖:
```xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- 或者如果你选择手动添加mybatis -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<!-- 如果你的数据库不是MySQL,替换为对应的JDBC驱动 -->
</dependency>
</dependencies>
```
然后,创建一个Mapper接口,例如UserMapper.java:
```java
import org.apache.ibatis.annotations.Select;
public interface UserMapper {
@Select("SELECT * FROM user WHERE id = #{id}")
User getUser(int id);
}
```
接着,配置数据源和MyBatis扫描路径,通常放在application.properties文件中:
```properties
spring.datasource.url=jdbc:mysql://localhost:3306/test?serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=password
mybatis.mapper-locations=classpath:mapper/*.xml
```
最后,在服务层启动时注入Mapper并使用它:
```java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserService {
private final UserMapper userMapper;
@Autowired
public UserService(UserMapper userMapper) {
this.userMapper = userMapper;
}
public User getUserById(int id) {
return userMapper.getUser(id);
}
}
```
阅读全文