Spring Boot 系列 | 第四篇:构建一个Restful API以及集成Mybatis访问数据库
2018-02-07 19:34
796 查看
Spring Boot 系列 | 第四篇:构建一个Restful API以及集成Mybatis访问数据库
前言
本文不算原创(参考了网上相关博客资料),也不做任何声明,仅仅是作为笔者的笔记记录。本节将会实现一个对
User资源操作的
Restful Api,来了解
Controller的编写以及
Mybatis的集成。
准备工作
Restful API设计如下
METHOD | URL | Description |
---|---|---|
GET | /users/ | 获取所有用户 |
GET | /users/id | 获取特定用户 |
POST | /users/ | 添加用户 |
PUT | /users/id | 修改用户 |
DELETE | /users/id | 删除用户 |
test,创建表
user
SET NAMES utf8mb4; SET FOREIGN_KEY_CHECKS = 0; -- ---------------------------- -- Table structure for `User` -- ---------------------------- DROP TABLE IF EXISTS `User`; CREATE TABLE `User` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(20) NOT NULL, `age` int(3) DEFAULT '0', PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8; SET FOREIGN_KEY_CHECKS = 1;
创建了一个用户表分别有
id,
name,
age字段
使用Mybatis访问数据库
引入mybatis依赖
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.0</version> </dependency>
在
application.properties中添加数据库连接配置:
spring.datasource.url=jdbc:mysql://localhost:3306/test?verifyServerCertificate=false&useSSL=false&requireSSL=false&useUnicode=true&characterEncoding=UTF-8&characterSetResults=utf8 spring.datasource.username=root spring.datasource.password=root spring.datasource.driver-class-name=com.mysql.jdbc.Driver
编写
UserMapper:
@Mapper public interface UserMapper { @Insert("insert into user(name, age) values(#{name}, #{age})") //指定生成返回ID @Options(useGeneratedKeys = true, keyProperty = "id", keyColumn = "id") Long add(User user); @Update("update user set name = #{name}, age=#{age} where id = #{id}") int update(User user); @Delete("delete from user where id = #{id}") int delete(int id); @Select("select id, name, age from user where id = #{id}") User findUser(int id); @Select("select id, name, age from user") List<User> findUsers(); }
编写
UserService:
@Service public class UserService { @Autowired UserMapper userMapper; public Long add(User user) { return userMapper.add(user); } public int update(User user) { return userMapper.update(user); } public int delete(int id) { return userMapper.delete(id); } public User findUser(int id) { return userMapper.findUser(id); } public List<User> findUsers() { return userMapper.findUsers(); } }
我这里为了省略直接编写方法了,实际开发中不可省略(需要声明一个
UserService接口和一个
UserServiceImpl)
编写Controller
在编写Controller的时候会用到以下注解
@Controller修饰
class,表明是一个控制器,通常用于
http请求,网页资源等。
@RestController
Spring 4之后加入的注解,原来在
@Controller中返回
json数据需要
@ResponseBody配合,用了
@RestController之后就不能配置
@ResponseBody,相当于
@Controller和
@ResponseBody的结合。
@RequestMapping
URL映射配置,修饰
class,表示当前
class的方法都是这个域,通常用于给不同的
Controller添加
@RequestMapping来标识不同的模块,修饰方法的时候,表示这个方法的
URL映射
@GetMapping相当于
@RequestMapping(value="/xxx",method = RequestMethod.GET)
@PostMapping相当于
@RequestMapping(value="/xxx",method = RequestMethod.POST)
@PutMapping相当于
@RequestMapping(value="/xxx",method = RequestMethod.PUT)
@DeleteMapping相当于
@RequestMapping(value="/xxx",method = RequestMethod.DELETE)
编写
Controller示例:
@RestController @RequestMapping("/users") public class UserController { @Autowired UserService userService; @GetMapping(value = "/") public List<User> getUsers() { return userService.findUsers(); } @GetMapping("/{id}") public User getUserById(@PathVariable int id) { return userService.findUser(id); } @PostMapping("/") public int addUser(User user) { userService.add(user); //返回增加后的id return user.getId(); } @PutMapping("/{id}") public String updateUser(@PathVariable int id, User user) { user.setId(id); int result = userService.update(user); return result == 1 ? "更新成功" : "更新失败"; } @DeleteMapping("/{id}") public String deleteUser(@PathVariable int id) { int result = userService.delete(id); return result == 1 ? "删除成功" : "删除失败"; } }
验证Restful API是否正确
引入测试依赖<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency>
在
src/test下新建一个
UserControllerTest.java:
@RunWith(SpringRunner.class) @SpringBootTest @AutoConfigureMockMvc public class UserControllerTest { @Autowired private MockMvc mvc; @Test public void testUserController() throws Exception { RequestBuilder request = null; // 1、get查一下user列表,应该为空 request = MockMvcRequestBuilders.get("/users/"); mvc.perform(request) .andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.content().string(Matchers.equalTo("[]"))); // 2、post提交一个user,得到这个user的id request = MockMvcRequestBuilders.post("/users/") .param("name", "wangjianfeng") .param("age", "12"); MvcResult mvcResult = mvc.perform(request) .andReturn(); String userId = mvcResult.getResponse().getContentAsString(); //根据这个ID查询用户,验证用户信息 request = MockMvcRequestBuilders.get("/users/" + userId); mvc.perform(request) .andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.jsonPath("name").value("wangjianfeng")) .andExpect(MockMvcResultMatchers.jsonPath("age").value("12")); //修改用户的年龄为20 request = MockMvcRequestBuilders.put("/users/" + userId) .param("name", "wangjianfeng") .param("age", "20"); mvc.perform(request) .andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.content().string(Matchers.equalTo("更新成功"))); //删除这个用户 request = MockMvcRequestBuilders.delete("/users/" + userId); mvc.perform(request) .andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.content().string(Matchers.equalTo("删除成功"))); } }
至此已经通过引入
Web/Mybatis/test模块进行了
Restful Api的编写和数据库访问以及测试结果的功能。
相关文章推荐
- SpringBoot学习系列 | 构建一个较为复杂的RESTful API以及单元测试
- SpringCloud SpringBoot mybatis 分布式微服务(二十六)集成swagger2构建Restful API
- Spring Boot集成MyBatis访问数据库
- Spring Boot系列六 Spring boot集成mybatis、分页插件pagehelper
- Spring Cloud Spring Boot mybatis分布式微服务云架构(九)使用Swagger2构建强大的RESTful API文档(1)
- Spring Boot干货系列:(九)数据存储篇-SQL关系型数据库之MyBatis的使用
- Spring Cloud Spring Boot mybatis分布式微服务云架构(九)使用Swagger2构建强大的RESTful API文档(1)
- springboot集成swagger2,构建强大的RESTful API文档
- 企业级 SpringBoot 教程 (十一)springboot集成swagger2,构建优雅的Restful API
- Spring Cloud Spring Boot mybatis分布式微服务云架构(五)构建RESTful API
- SpringCloud SpringBoot mybatis 分布式微服务(三十)springboot集成swagger2,构建优雅的Restfu API
- SpringBoot非官方教程 | 第十一篇:springboot集成swagger2,构建优雅的Restful API
- Spring Cloud Spring Boot mybatis分布式微服务云架构(十)使用Swagger2构建强大的RESTful API文档(2)
- SpringBoot非官方教程 | 第十一篇:springboot集成swagger2,构建优雅的Restful API
- Spring Boot 学习笔记4——结合Mybatis访问数据库及事务控制
- SpringCloud SpringBoot mybatis 分布式微服务(八)Spring Boot中使用JdbcTemplate访问数据库
- Spring Boot 构建一个较为复杂的RESTful API以及单元测试
- 【Spring Boot&&Spring Cloud系列】提高数据库访问性能
- [置顶] MyBatis基于Spring-boot集成通用Mapper以及pagehelper分页插件(含源码下载)
- Spring Cloud Spring Boot mybatis分布式微服务云架构(九)使用Swagger2构建强大的RESTful API文档(1)