springboot+mybatis实现查询代码
时间: 2023-12-11 08:04:02 浏览: 97
Springboot集成MyBatis实现查询表操作
可以按照以下步骤实现基于Spring Boot和MyBatis的查询功能:
1. 首先,需要在pom.xml文件中添加Spring Boot和MyBatis的依赖项:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.0.0</version>
</dependency>
```
2. 在application.properties文件中配置MyBatis连接数据库的相关信息:
```properties
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/mydatabase
spring.datasource.username=root
spring.datasource.password=root
```
3. 创建一个Mapper接口,定义查询方法:
```java
@Mapper
public interface UserMapper {
@Select("SELECT * FROM user WHERE id = #{id}")
User findById(@Param("id") Long id);
}
```
4. 创建一个Service类,调用Mapper接口的查询方法:
```java
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public User findById(Long id) {
return userMapper.findById(id);
}
}
```
5. 在Controller中注入Service,调用查询方法:
```java
@RestController
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/user/{id}")
public User findById(@PathVariable Long id) {
return userService.findById(id);
}
}
```
以上就是基于Spring Boot和MyBatis实现查询功能的代码实现过程。
阅读全文