springboot+mybatis接口案例
时间: 2023-12-08 17:03:10 浏览: 39
好的,这里提供一个简单的SpringBoot+Mybatis接口案例。
1. 首先,创建一个SpringBoot项目,可以使用IDEA或Eclipse等集成开发环境进行创建。
2. 在pom.xml文件中添加SpringBoot和Mybatis的依赖:
```
<dependencies>
<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.1.4</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.26</version>
</dependency>
</dependencies>
```
其中,spring-boot-starter-web是SpringBoot的Web模块,mybatis-spring-boot-starter是Mybatis的SpringBoot集成模块,mysql-connector-java是MySQL的JDBC驱动。
3. 创建一个数据表,并在MySQL数据库中插入一些数据,例如:
```
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
`age` int(11) NOT NULL,
PRIMARY KEY (`id`)
);
INSERT INTO `user` (`name`, `age`) VALUES ('张三', 20);
INSERT INTO `user` (`name`, `age`) VALUES ('李四', 25);
INSERT INTO `user` (`name`, `age`) VALUES ('王五', 30);
```
4. 创建一个实体类User,用于映射数据表中的数据:
```
public class User {
private int id;
private String name;
private int age;
// getter和setter方法省略
}
```
5. 创建一个Mapper接口UserMapper,用于定义对User表操作的方法:
```
@Mapper
public interface UserMapper {
@Select("SELECT * FROM user")
List<User> getAllUsers();
}
```
其中,@Mapper注解是Mybatis提供的,可以将该接口声明为一个Mapper接口,@Select注解表示查询语句。
6. 创建一个Service接口UserService,用于调用Mapper接口中的方法:
```
public interface UserService {
List<User> getAllUsers();
}
```
7. 创建UserService的实现类UserServiceImpl,注入UserMapper接口,并实现UserService接口中的方法:
```
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public List<User> getAllUsers() {
return userMapper.getAllUsers();
}
}
```
其中,@Service注解表示该类为Spring的Service类,@Autowired注解表示自动注入UserMapper接口。
8. 创建一个Controller类UserController,用于接收前端请求并调用UserService的方法:
```
@RestController
@RequestMapping("/users")
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/")
public List<User> getAllUsers() {
return userService.getAllUsers();
}
}
```
其中,@RestController注解表示该类为Spring的RestController类,@RequestMapping注解表示请求的URL,@GetMapping注解表示GET请求。
9. 运行SpringBoot应用程序,在浏览器中输入"http://localhost:8080/users/"即可访问接口,获取User表中的所有数据。
以上就是一个简单的SpringBoot+Mybatis接口案例,其中包括了数据表的创建、Mybatis的使用、Service和Controller的编写等内容,希望对你有帮助。