linux cpu占用率如何看
225
2022-11-15
SpringBoot+Mybatis整合(三)-最终版(整合了Swagger)
目录
创建SpringBoot工程
新建一个project
新建一个module
准备数据库
新建数据库
新建用户表t_user
插入测试数据
整合Mybatis
添加相应Jar包
代码实现
User
dao(UserMapper)
mapper.xml
UserService
UserService
UserController
application.properties
验证
整合Swagger
Swagger是什么?
集成Swagger相关依赖包
创建Swagger相关Docket Bean
在controller层添加Swagger的注解,让spring自动加载识别
创建SpringBoot工程
这次我们用IDEA来做开发工具,IDEA有一个很大优势就是可以建一个project,然后下面有多个module,这种特性对于我们做Java开发非常方便,尤其是做微服务开发的时候,方便联调。
新建一个project
我们先采取默认的maven工程,以后需要哪些组件,后续再加。
这样,我们就建好了一个projec,我们建这个project主要是用于目录作用,不在里加业务代码。因此,后续我们要往里加相应的模块module就可以。
新建一个module
可能不同版本的IDEA,界面会有点不一样,但基本意思大概相同,所以遇到不一样界面的朋友们,认真细看比对一下就可以。
有些版本的IDEA,“Spring Web”那里可能是“WEB”,其实都是一样的。
如果你自己电脑没有相应maven库,可能要稍微等一会。
从上图可知,已成功新建好module,那我们测试一下,看看是否已经成功搭建好。
我们运行一下,看看效果。
默认是8080端口,我们在浏览器访问一下。
TABLE `t_user` ( `id` int NOT NULL AUTO_INCREMENT COMMENT 'id,主键', `name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '用户名', `age` int DEFAULT NULL COMMENT '年龄', PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8;
插入测试数据
为了方便调试,我们先插入一些测试数据。
大家也可以通过命令语句实现。
INSERT INTO `t_user` (`name`, `age`) VALUES ('zhangsan', '20')INSERT INTO `t_user` (`name`, `age`) VALUES ('lisi', '25')
整合Mybatis
添加相应Jar包
先添加Mybatis相关包:
由于我们选用的数据库是Mysql,所以还需要把mysql相关包添加进去。
代码实现
SpringBoot主要是用于web项目,所以我们这次从web项目开发流程来完成代码编写。
一般而言,web项目一般分为三大层controller、service、dao。那我们应该从哪边写起呢?说句实话,没有强制性的要求,但大部分开发者,可能都会从controller这层开始写起,往dao那边写。然后又倒回来完善controller这边。但这次为了演示,我们的业务代码都会比较简单,我就反过来写,先把dao这块写好。写dao层之前,我先贴出项目的包结构。
User
我们这次用个比较经典的实体类,与数据库的t_user表匹配。
package com.ispeasant.demo.entity;/** * User实体类 */public class User { private int id; // id private String name; // 用户名 private int age; // 年龄 public int getId() { return id; } public String getName() { return name; } public int getAge() { return age; } public void setId(int id) { this.id = id; } public void setName(String name) { this.name = name; } public void setAge(int age) { this.age = age; }}
在项目中,我们经常都需要创建实体类,一般都要写get/set方法,大家要灵活应用开发工作,提高编码效率。
dao(UserMapper)
package com.ispeasant.demo.dao;import com.ispeasant.demo.entity.User;import org.apache.ibatis.annotations.Mapper;/** * UserMapper */@Mapperpublic interface UserMapper { User getUserById(int id);}
这里要注意的是,必须要使用“@Mapper"的注解,同时还需要配置对应的mapper.xml文件,不然spring无法扫描到。
mapper.xml
拆分说明:
这部分是要和你的dao接口对应上,直接拷贝全路径。
这块是按需来弄,也有可能会多几个不同的定义。有些朋友对这部分可能会比较难理解,我自己也是这样跟我团队说的,你们就把这块看做是这个配置文件里的实体对象,方便数据交互。
select标签的id要和UserMapper的方法对应上,然后在里面写对应的业务sql逻辑。
UserService
package com.ispeasant.demo.service;import com.ispeasant.demo.entity.User;public interface UserService { User getUserById(int id);}
在javaEE代码规范中,我们一般都会把service层封装为两层,一层是接口层,另一层是实现层,这样可以方便解耦业务代码。
UserService
package com.ispeasant.demo.service.impl;import com.ispeasant.demo.dao.UserMapper;import com.ispeasant.demo.entity.User;import com.ispeasant.demo.service.UserService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;@Servicepublic class UserSeviceImpl implements UserService { @Autowired private UserMapper userMapper; @Override public User getUserById(int id) { User user = userMapper.getUserById(id); return user; }}
我们要先实现UserService接口,并重写里面的方法。需要把UserMapper自动装载进来,采用"@Autowired"注解。
在类上面,我们要采用”@Service“注解,这样才会被spring注入到controller层。
UserController
package com.ispeasant.demo.controller;import com.ispeasant.demo.entity.User;import com.ispeasant.demo.service.UserService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RestController;@RestControllerpublic class UserController { @Autowired private UserService userService; @GetMapping("/getUserById") public User getUserById(int id){ User user = userService.getUserById(id); return user; }}
Controller层和service层有点类似,也是需要自动装载UserService,采用”@Autowired“注解。
在类的上面,也需要添加“@RestController”,它是responseboby+ controller俩个注解的合体。
@GetMapping封装API接口定义。@GetMapping注释将 HTTP GET 请求映射到特定的处理程序方法。 它是一个组合的注释,用作@RequestMapping(method = RequestMethod.GET)的快捷方式。
application.properties
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driverspring.datasource.url=jdbc:mysql://10.18.0.57:3306/springbootmybatisDBspring.datasource.username=rootspring.datasource.password=123456mybatis.type-aliases-package=com.ispeasant.demo.entitymybatis.mapperLocations=classpath:mappers/*.xml
最后还需要配置数据库相关信息,由于我是用mysql8,所以驱动要用“com.mysql.cj.jdbc.Driver”,如果是其它低版本的数据库,可采用“com.mysql.jdbc.Driver”。
最后那里还要配置实体包路径以及mapper文件路径(采取通配方式)。
验证
在浏览器打开以下链接:
Development for Everyone
Simplify API development for users, teams, and enterprises with the Swagger open source and professional toolset. Find out how Swagger can help you design and document your APIs at scale.
大概意思是Swagger是用于API开发,类似我们以前写API文档那样,方便开发团队协作开发。
作用:
自动生成接口的文档。接口测试
集成Swagger相关依赖包
在pom.xml文件添加以下内容。
创建Swagger相关Docket Bean
package com.ispeasant.demo.config;import io.swagger.annotations.ApiOperation;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import springfox.documentation.builders.ApiInfoBuilder;import springfox.documentation.builders.RequestHandlerSelectors;import springfox.documentation.service.ApiInfo;import springfox.documentation.spi.DocumentationType;import springfox.documentation.spring.web.plugins.Docket;import springfox.documentation.swagger2.annotations.EnableSwagger2;@Configuration@EnableSwagger2public class SpringFoxSwaggerConfig { @Bean public Docket swaggerSpringMvcPlugin() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class)) .build().apiInfo(apiInfo()) ; } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("RESTful API") .description("基础管理") .termsOfServiceUrl("") .version("1.0") .build(); }}
我们先运行一下代码,看看效果。直接运行“DemoApplication”这个类,然后在浏览器输入Swagger UI的链接:Bean,然后再用apiInfo()方法创建整个API的基本信息,也就是我们在上面看到的信息。
我们还可以再用浏览器打开以下链接,查看已经生成了描述API的swagger元数据。
Demo"},"host":"localhost:8080","basePath":"/"}
内容看得有点吃力,所以我们还是用最上面那个UI界面好一些。
在controller层添加Swagger的注解,让spring自动加载识别
package com.ispeasant.demo.controller;import com.ispeasant.demo.entity.User;import com.ispeasant.demo.service.UserService;import io.swagger.annotations.Api;import io.swagger.annotations.ApiImplicitParam;import io.swagger.annotations.ApiImplicitParams;import io.swagger.annotations.ApiOperation;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.RestController;@RestController@Api(value = "用户模块", description = "用户模块接口")public class UserController { @Autowired private UserService userService; @RequestMapping(value = "/getUserById", method = RequestMethod.GET) @ApiOperation(value = "根据用户ID获取用户", notes = "查询") @ApiImplicitParams({@ApiImplicitParam(name = "id",value = "主键id",required = true,paramType = "query",dataType = "int")}) public User getUserById(int id) { User user = userService.getUserById(id); return user; }}
我们也可以在Swagger的web UI界面测试接口。
从上图可知,我们已经成功完全集合了Swagger。
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~