需要实现的功能
- 登录
- 根据id查询
- 添加用户
- 修改⽤户数据
- 根据id删除用户
- 批量删除⽤户数据
- 分页查询
- 多条件分页查询
生产方
环境搭建
https://blog.csdn.net/qq_44509920/article/details/107738382
- pom.xml
<parent><!--StringBoot 父工程-->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<build>
<plugins>
<plugin>
<!--StringBoot Maven插件-->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<!-- 统一版本维护 -->
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<mybatis.starter.version>1.3.2</mybatis.starter.version>
<mapper.starter.version>2.0.2</mapper.starter.version>
<mysql.version>5.1.32</mysql.version>
<pageHelper.starter.version>1.2.5</pageHelper.starter.version>
<durid.starter.version>1.1.10</durid.starter.version>
</properties>
<dependencies>
<!-- SpringBoot整合SpringMVC的启动器 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- SpringBoot整合jdbc和事务的启动器 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!-- mybatis启动器 -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>${mybatis.starter.version}</version>
</dependency>
<!-- 通用Mapper启动器 -->
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper-spring-boot-starter</artifactId>
<version>${mapper.starter.version}</version>
</dependency>
<!-- 分页助手启动器 -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>${pageHelper.starter.version}</version>
</dependency>
<!-- mysql驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<!-- Druid连接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>${durid.starter.version}</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.10</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.4</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.11</version>
</dependency>
</dependencies>
- application.properties
或者application.yaml
#Tomcat
server.port=8080
#DB configuration
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/222?useUnicode=true&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=root
#druid
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.druid.initial-size=1
spring.datasource.druid.min-idle=1
spring.datasource.druid.max-active=20
spring.datasource.druid.test-on-borrow=true
spring.datasource.druid.stat-view-servlet.allow=true
创建数据库表
CREATE TABLE `user`(
`uid` int PRIMARY KEY AUTO_INCREMENT COMMENT "⽤户ID",
`username` varchar(32) NOT NULL UNIQUE COMMENT "⽤户名",
`password` varchar(32) NOT NULL COMMENT "密码",
`sex` varchar(1) NOT NULL COMMENT "性别",
`age` int NOT NULL COMMENT "年龄",
`remarks` varchar(200)
);
INSERT INTO `user` (uid, username, password, sex, age, remarks) VALUES(1,
'zs', '123', '男', 23, '他说他是个男⼈');
INSERT INTO `user` (uid, username, password, sex, age, remarks) VALUES(2,
'ls', '123', '男', 24, '他是个也是个男⼈');
INSERT INTO `user` (uid, username, password, sex, age, remarks) VALUES(3, '王 五', '123', '⼥', 25, '⼲,就完了');
INSERT INTO `user` (uid, username, password, sex, age, remarks) VALUES(4,
'Jack', '123', '男', 20, '奥⼒给');
- 目录
生产端代码实现
- 工具类
Result工具类
package com.czxy.util;
import lombok.Data;
import java.util.HashMap;
import java.util.Map;
//@ApiModel(value = "全局统一返回结果")
@Data//get set
public class Result {
private boolean success;//true 成功 false 失败
private ResultCodeEnum code;//状态码 20000 成功 20001 失败
private String message;//成功或者失败的消息
private Map<String,Object> data = new HashMap<String, Object>();//用来存放数据
/**
* 成功的方法:基本的数据设定在这个方法中完成
*/
public static Result ok(){
Result result = new Result();
result.setSuccess(true);
result.setCode(ResultCodeEnum.SUCCESS);
result.setMessage("成功");
return result;
}
/**
* 错误的方法
*/
public static Result error(){
Result result = new Result();
result.setSuccess(false);
result.setCode(ResultCodeEnum.FAIL);
result.setMessage("失败");
return result;
}
/**
* 所谓的data方法就是向Map<String,Object> data 集合中加入数据
*/
public Result data(String key,Object value){
this.data.put(key,value);
return this;//this代表当前对象
}
public Result message(String msg){
this.setMessage(msg);
return this;//this代表当前对象
}
}
- 枚举类
package com.czxy.util;
/**
* 方式2:枚举
*/
public enum ResultCodeEnum {
SUCCESS,
FAIL
}
- 扩展类(多条件分页查询需要)
package com.czxy.vo;
import lombok.Data;
@Data
public class QueryUserVo {
private String username;//姓名
private Integer min;//最小年龄
private Integer max;//最大年龄
}
- 创建类
package com.czxy.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Data//相当于拥有了getter、setter、toString方法
@AllArgsConstructor//全参构造
@NoArgsConstructor//空参构造
@Table(name = "user")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)//主键策略:
private Integer uid;
private String username;
private String password;
private String sex;
private Integer age;
private String remarks;
}
- 创建接口
package com.czxy.dao;
import com.czxy.pojo.User;
import tk.mybatis.mapper.common.Mapper;
@org.apache.ibatis.annotations.Mapper
public interface UserMapper extends Mapper<User> {
}
- 业务逻辑
package com.czxy.service;
import com.czxy.dao.UserMapper;
import com.czxy.pojo.User;
import com.czxy.util.Result;
import com.czxy.vo.QueryUserVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;
import java.util.List;
@Service
@Transactional//事务
public class UserService {
@Autowired
private UserMapper userMapper;
/**
* 1.登录
* 根据用户名查找用户信息
*/
public User findUserByUsername(String username){
//1通用mapper条件查询,需要使用Example
Example example = new Example(User.class);
//2添加条件
example.createCriteria().andEqualTo("username",username);
//3执行查询
User user = userMapper.selectOneByExample(example);
//4返回
return user;
}
/**
*2.根据id查询
*/
public User findById(Integer id){
return userMapper.selectByPrimaryKey(id);
}
/**
* 3.添加用户
*/
public void addUser(User user){
userMapper.insert(user);
}
/**
* 4. 修改用户
*/
public boolean updeteUser(User user){
int i = userMapper.updateByPrimaryKey(user);
return i==1;
}
/**
* 5.根据id删除
*/
public void deleteUser(Integer id){
userMapper.deleteByPrimaryKey(id);
}
/**
* 6. 批量删除
*/
public void deleteUser(String ids){
String[] idStrs = ids.split(",");
for(String id:idStrs){
userMapper.deleteByPrimaryKey(Integer.parseInt(id));
}
}
/**
* 7. 分页查询
* 分页需要两个参数:page页码 limit/rows 每页条数
*/
public Result findByPage(Integer page,Integer limit){
/**
* 使用PageHelper分页助手
* 这行代码对紧跟着他的第一条SQL语句起作用
* PageHelper实现原理是什么?
* 答:SpringAOP 的思想,切面拦截,进行功能增强
* AOP:在不改变项目原有代码、原有业务的基础上,对功能进行增强
*/
//1分页
PageHelper.startPage(page,limit);
//2执行查询
List<User> list = userMapper.select(null);
//3封装分页结果 total该分页中的数据
PageInfo<User> pageInfo = new PageInfo<>(list);
//4获取总条数
long total = pageInfo.getTotal();
//5获取该页中的数据
List<User> pageList = pageInfo.getList();
//6封装结果
return Result.ok().message("分页查询成功")
.data("total",total)
.data("page",page)
.data("pageSize",limit)
.data("list",pageList);
}
/**
* 8. 多条件分页查询
*/
public Result findByPage2(Integer page, Integer limit, QueryUserVo queryUserVo){
/**
* 使用PageHelper分页助手
* 这行代码对紧跟着他的第一条SQL语句起作用
* PageHelper实现原理是什么?
* 答:SpringAOP 的思想,切面拦截,进行功能增强
* AOP:在不改变项目原有代码、原有业务的基础上,对功能进行增强
*/
PageHelper.startPage(page,limit);
Example example = new Example(User.class);
Example.Criteria criteria = example.createCriteria();
/**
* 拼接条件
*/
String username = queryUserVo.getUsername();
Integer min = queryUserVo.getMin();
Integer max = queryUserVo.getMax();
// if(username!=null&&!"".equals(username.trim())){}
if(StringUtils.isNotBlank(username)&&!"null".equals(username)){
criteria.andLike("username","%"+username+"%");
}
//范围查询 >=
if(min!=null){
//andGreaterThanOrEqualTo 大于等于
criteria.andGreaterThanOrEqualTo("age",min);
}
if(max!=null){
//andLessThanOrEqualTo 小于等于
criteria.andLessThanOrEqualTo("age",max);
}
// userMapper.selectAll()
//2 执行查询
List<User> list = userMapper.selectByExample(example);//发出sql语句 select * from user limit 2,5
//3 封装分页结果 total 该页中的数据
PageInfo<User> pageInfo = new PageInfo<>(list);
//4 获取总条数
long total = pageInfo.getTotal();
//5 获取该页中的数据
List<User> pageList = pageInfo.getList();
//6 封装结果
return Result.ok().message("分页查找成功")
.data("total",total)
.data("page",page)
.data("pageSize",limit)
.data("list",pageList);
}
}
- 接收页面数据
package com.czxy.controller;
import com.czxy.pojo.User;
import com.czxy.service.UserService;
import com.czxy.util.Result;
import com.czxy.vo.QueryUserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
/**
* 1登录
* http://localhost:8080/user/login
*/
@PostMapping("/login")
public Result login(@RequestBody User user){
User dbUser = userService.findUserByUsername(user.getUsername());
if (dbUser!=null){
if (dbUser.getPassword().equals(user.getPassword())){
return Result.ok().message("登录成功").data("user",user);
}
}
return Result.error().message("用户名或者密码错误");
}
/**
* 2 根据id查询
* id :表示传入的参数
* http://localhost:8080/user/1
*/
@GetMapping("/{id}")
public Result findById(@PathVariable("id") Integer id){
User user = userService.findById(id);
if(user!=null){
return Result.ok().data("user",user);
}
return Result.error();
}
/**
* 3 添加用户
*/
@PostMapping("/add")
public Result addUser(@RequestBody User user){
userService.addUser(user);
return Result.ok().data("user",user).message("添加成功");
}
/**
* 4. 修改用户
*/
@PutMapping
public Result updedeUser(@RequestBody User user){
boolean flag = userService.updeteUser(user);
if (flag){
return Result.ok().data("flag",flag);
}
return Result.error().message("修改失败");
}
/**
* 5.根据id删除
* 两个 @DeleteMapping 一样 只能选择一个运行
*/
@DeleteMapping("/{id}")
public Result deleteUser(@PathVariable("id") Integer id){
userService.deleteUser(id);
return Result.ok().data("id",id).message("删除成功");
}
/**
* 6. 批量删除
*/
// @DeleteMapping("/{ids}")
// public Result deleteUser(@PathVariable String ids){
// userService.deleteUser(ids);
// return Result.ok();
// }
/**
* 7. 分页查询
* 年龄等于18
* http://localhost:8080/user/1/2?age=18
*/
@GetMapping("/{page}/{limit}")
public Result findByPage(@PathVariable("page") Integer page,@PathVariable("limit") Integer limit){
try {
//调用service
Result result = userService.findByPage(page, limit);
return result;
} catch (Exception e) {
return Result.error();
}
}
/**
* 8. 多条件分页查询
* 模糊查询姓名为s和年龄大小
* http://localhost:8080/user/1/2?username=s&min=24&max=33
*/
// @GetMapping("/{page}/{limit}")
// public Result findByPage2(@PathVariable("page") Integer page, @PathVariable("limit") Integer limit,QueryUserVo queryUserVo){
// try {
// //调用Service
// Result result = userService.findByPage2(page, limit,queryUserVo);
// return result;
// }catch (Exception e){
// return Result.error();
// }
// }
}
- 运行测试
package com.czxy;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Demo01Application {
public static void main(String[] args) {
SpringApplication.run(Demo01Application.class, args);
}
}
Postman生产端测试
-
登录
-
根据id查询
-
添加用户
-
修改用户数据
-
根据id删除
-
批量删除
-
分页查询
-
多条件分页查询
消费方
环境搭建
https://blog.csdn.net/qq_44509920/article/details/107738198
- pom.xml
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<spring-boot.version>2.3.0.RELEASE</spring-boot.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--get set -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.10</version>
</dependency>
<!--test-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
- application.properties
server.port=8090
- 目录
消费端代码实现
两端服务器都要运行
- 工具类
package com.czxy.util;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
/**
* RestTemplate工具类,主要用来提供RestTemplate对象
*/
@Configuration//加上这个注解作用,可以被Spring扫描
public class RestTemplateConfig {
/**
* 创建RestTemplate对象,将RestTemplate对象的生命周期的管理交给Spring
*/
@Bean
public RestTemplate restTemplate(){
// RestTemplate restTemplate = new RestTemplate();
//设置中文乱码问题方式一
// restTemplate.getMessageConverters().add(1,new StringHttpMessageConverter(Charset.forName("UTF-8")));
// 设置中文乱码问题方式二
// restTemplate.getMessageConverters().set(1,new StringHttpMessageConverter(StandardCharsets.UTF_8)); // 支持中文编码
return new RestTemplate();
}
}
- 创建实体类
package com.czxy.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data//相当于拥有了getter、setter、toString方法
@AllArgsConstructor//全参构造
@NoArgsConstructor//空参构造
public class User {
private Integer uid;
private String username;
private String password;
private String sex;
private Integer age;
private String remarks;
}
- VO扩展类
package com.czxy.vo;
import lombok.Data;
@Data
public class QueryUserVo {
private String username;
private Integer min;//最小年龄
private Integer max;//最大年龄
}
- 消费端接收用户数据
消费端必须与生产端的 请求类型 保持一致
package com.czxy.controller;
import com.czxy.pojo.User;
import com.czxy.vo.QueryUserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
@RestController
@RequestMapping("/user2")
public class RestTempController {
@Autowired
private RestTemplate restTemplate;
/**
* 1 登录
*/
@PostMapping("/login")
public ResponseEntity<String> login(@RequestBody User user){
ResponseEntity<String> entity = restTemplate.postForEntity("http://localhost:8080/user/login", user, String.class);
return entity;
}
/**
* 2 根据id查询
* /{id} 传入参数
*/
@GetMapping("/{id}")
public ResponseEntity<String>findByUser(@PathVariable Integer id){
ResponseEntity<String> entity = restTemplate.getForEntity("http://localhost:8080/user/" + id, String.class);
return ResponseEntity.ok(entity.getBody());
}
/**
* 3 添加用户
*/
@PostMapping("/add")
public ResponseEntity<String>addUser(@RequestBody User user){
return restTemplate.postForEntity("http://localhost:8080/user/add", user, String.class);
}
/**
* 4 修改用户数据
* 消费端必须与生产端的 PutMapping 保持一致
*/
@PutMapping
public ResponseEntity<String>updataUser(@RequestBody User user){
restTemplate.put("http://localhost:8080/user",user);
return new ResponseEntity<>("修改成功",HttpStatus.OK);
}
/**
* 5 根据id删除
* 两个 @DeleteMapping 一样 只能选择一个运行
*/
@DeleteMapping("/{id}")
public ResponseEntity<String>deleteUser(@PathVariable Integer id){
restTemplate.delete("http://localhost:8080/user/"+id,String.class);
return ResponseEntity.ok("删除成功");
}
/**
* 6 批量删除
* /{ids} 传入参数
*/
// @DeleteMapping("/{ids}")
// public ResponseEntity<String> delUser(@PathVariable("ids") String ids) {
// restTemplate.delete("http://localhost:8080/user/" + ids);
// return new ResponseEntity<>("删除成功", HttpStatus.OK);
// }
/**
* 7 分页查询
* 年龄等于18
* http://localhost:8080/user/1/2?age=18
*/
@GetMapping("/{page}/{limit}")
public ResponseEntity<String>findBypage(@PathVariable Integer page,@PathVariable Integer limit){
restTemplate.getForEntity("http://localhost:8080/user/" + page + "/" + limit,String.class);
return ResponseEntity.ok("查询成功");
}
/**
* 8 多条件分页查询
* 模糊查询姓名为s和年龄大小
* http://localhost:8080/user/1/2?username=s&min=24&max=33
*/
// @GetMapping("/{page}/{limit}")
// public ResponseEntity<String> findByPage(@PathVariable Integer page,
// @PathVariable Integer limit,
// QueryUserVo queryUserVo){
String value = restTemplate.getForObject("http://localhost:8090/user/" + page + "/" + limit, String.class, queryUserVo);
// String url = "http://localhost:8080/user/" + page + "/" + limit+"?username="+queryUserVo.getUsername();
// Integer min = queryUserVo.getMin();
// Integer max = queryUserVo.getMax();
// if(min!=null){
// url+="&min="+min;
// }
// if(max!=null) {
// url += "&max=" + max;
// }
// String value = restTemplate.getForObject(url, String.class);
// return ResponseEntity.ok(value);
// }
}
- 运行测试
package com.czxy;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Demo001Application {
public static void main(String[] args) {
SpringApplication.run(Demo001Application.class, args);
}
}
Postman消费端测试
-
登录
-
根据id查询
-
添加用户
-
修改
-
根据id删除
-
批量删除
-
分页查询
-
多条件分页查询