将 Mybaits 集成进当前的 springboot 项目
时间: 2023-05-30 15:06:42 浏览: 52
1. 添加 Mybatis 和 Mybatis-Spring 依赖
在 pom.xml 文件中添加以下依赖:
```xml
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.0</version>
</dependency>
```
2. 配置数据源信息
在 application.properties 或 application.yml 中配置数据源信息,例如:
```properties
spring.datasource.url=jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
```
3. 配置 Mybatis
在 application.properties 或 application.yml 中配置 Mybatis 相关配置,例如:
```properties
mybatis.mapper-locations=classpath:mapper/*.xml
mybatis.type-aliases-package=com.example.demo.entity
```
4. 创建 Mapper 接口和映射文件
创建 Mapper 接口和对应的映射文件,例如:
```java
public interface UserMapper {
User selectByPrimaryKey(Integer userId);
}
```
```xml
<mapper namespace="com.example.demo.mapper.UserMapper">
<resultMap type="com.example.demo.entity.User" id="UserResultMap">
<id column="user_id" property="userId"/>
<result column="user_name" property="userName"/>
<result column="user_age" property="userAge"/>
</resultMap>
<select id="selectByPrimaryKey" resultMap="UserResultMap" parameterType="java.lang.Integer">
select * from user where user_id = #{userId}
</select>
</mapper>
```
5. 注入 Mapper 接口
在需要使用 Mapper 接口的地方,使用 @Autowired 注解注入接口,例如:
```java
@RestController
public class UserController {
@Autowired
private UserMapper userMapper;
@GetMapping("/user/{userId}")
public User getUser(@PathVariable Integer userId) {
return userMapper.selectByPrimaryKey(userId);
}
}
```
以上就是将 Mybatis 集成进当前的 Spring Boot 项目的步骤。