SpringBoot集成mybatis。
时间: 2023-06-09 18:07:22 浏览: 50
可以通过以下步骤将SpringBoot与MyBatis集成:
1. 在pom.xml中添加相关的依赖:
```
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.0</version>
</dependency>
```
2. 在application.properties中配置数据库相关信息:
```
spring.datasource.url=jdbc:mysql://localhost:3306/mydatabase
spring.datasource.username=myusername
spring.datasource.password=mypassword
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
mybatis.mapper-locations=classpath:mapper/*.xml
mybatis.type-aliases-package=com.example.entity
```
3. 创建MyBatis Mapper接口和XML文件:
```
package com.example.mapper;
import com.example.entity.User;
@Mapper
public interface UserMapper {
@Select("SELECT * FROM user WHERE id = #{id}")
User findById(Long id);
}
```
```
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.mapper.UserMapper">
<resultMap id="userMap" type="com.example.entity.User">
<id column="id" property="id"/>
<result column="username" property="username"/>
<result column="password" property="password"/>
<result column="email" property="email"/>
</resultMap>
<select id="findById" resultMap="userMap">
SELECT * FROM user WHERE id = #{id}
</select>
</mapper>
```
4. 在Controller中调用Mapper方法:
```
@RestController
@RequestMapping("/users")
public class UserController {
@Autowired
private UserMapper userMapper;
@GetMapping("/{id}")
public User findById(@PathVariable Long id) {
return userMapper.findById(id);
}
}
```