,在springboot中如何集成mybatis.?
时间: 2024-05-03 19:19:33 浏览: 13
在Spring Boot中集成MyBatis,可以通过以下步骤实现:
1. 添加MyBatis和MyBatis-Spring-Boot-Starter依赖:
```
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.0</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.5</version>
</dependency>
```
2. 配置数据源
在application.yml文件中配置数据源,例如:
```
spring:
datasource:
url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false
username: root
password: root
driver-class-name: com.mysql.cj.jdbc.Driver
```
3. 配置MyBatis
在application.yml文件中配置MyBatis,例如:
```
mybatis:
mapper-locations: classpath:mapper/*.xml
```
4. 编写Mapper接口
编写Mapper接口,例如:
```
@Mapper
public interface UserMapper {
User getUserById(Long id);
}
```
5. 编写Mapper XML文件
编写Mapper XML文件,例如:
```
<mapper namespace="com.example.demo.mapper.UserMapper">
<select id="getUserById" parameterType="java.lang.Long" resultType="com.example.demo.model.User">
select * from user where id = #{id}
</select>
</mapper>
```
6. 注入Mapper
在需要使用Mapper的地方注入Mapper,例如:
```
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public User getUserById(Long id) {
return userMapper.getUserById(id);
}
}
```
通过以上步骤,就可以在Spring Boot中集成MyBatis了。