Java程序设计:spring boot(7)——数据访问操作

server/2024/10/23 3:59:44/

目录

1 查询操作

1.1 接口方法定义

1.2 映射文件配置

1.3 UserService

1.4 UserController

2 添加操作

2.1 接口方式定义

2.2 映射文件配置

2.3 添加 commons-lang3 依赖

2.4 AssertUtil ⼯具类

2.5 ParamsException ⾃定义异常

2.6 UserService

2.7 ResultInfo

2.8 UserController

3 修改操作

3.1 接口方法定义

3.2 映射文件配置

3.3 UserService

3.4 UserController

4 删除操作

4.1 接口方法定义

4.2 映射文件配置

4.3 UserService

4.4 UserController

5 分页条件查询操作

5.1 UserQuery

5.2 接口方法定义

5.3 映射文件配置

5.4 UserService

5.5 UserController

6 PostMan 工具下载与使用


完成 SpringBoot 与 Mybatis 集成后,以⽤户表为例实现⼀套⽤户模块基本数据维护。

1 查询操作

1.1 接口方法定义

UserMapper 接⼝添加查询的⽅法:

java">public interface UserMapper {// 通过⽤户ID查询⽤户public User queryById(Integer id);
}

1.2 映射文件配置

java"><?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.xxxx.springboot.dao.UserMapper"><select id="queryById" parameterType="int"resultType="com.xxxx.springboot.po.User">select*fromtb_userwhereid = #{id,jdbcType=INTEGER}</select>
</mapper>

1.3 UserService

java">@Service
public class UserService {@Resourceprivate UserMapper userMapper;/*** 通过⽤户ID查询⽤户* @param id* @return*/public User queryById(Integer id){return userMapper.queryById(id);}
}

1.4 UserController

java">@RestController
public class UserController {@Resourceprivate UserService userService;/*** 根据⽤户ID查询⽤户对象* @param userId* @return*/@GetMapping("user/{userId}")public User queryUserByUserId(@PathVariable Integer userId){return userService.queryById(userId);}
}

2 添加操作

2.1 接口方式定义

java">public interface UserMapper {// 添加⽤户public int save(User user);
}

2.2 映射文件配置

java"><?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.xxxx.springboot.dao.UserMapper"><insert id="save" parameterType="com.xxxx.springboot.po.User">insert intotb_user(user_name,user_pwd)values(#{userName},#{userPwd})</insert></mapper>

2.3 添加 commons-lang3 依赖

       如果需要使⽤ StringUtils ⼯具类,需要引⼊ commons-lang3 依赖。

java"><dependency><groupId>org.apache.commons</groupId><artifactId>commons-lang3</artifactId>
</dependency>

2.4 AssertUtil ⼯具类

java">package com.xxxx.springboot.utils;
import com.xxxx.springboot.exceptions.ParamsException;
public class AssertUtil {/*** 判断结果是否为true* 如果结果为true,抛出异常* @param userName* @return*/public static void isTrue(Boolean flag, String msg){if(flag){throw new ParamsException(msg);}}
}

2.5 ParamsException ⾃定义异常

java">package com.xxxx.springboot.exceptions;
/**
* ⾃定义参数异常
*/
public class ParamsException extends RuntimeException {private Integer code = 300;private String msg = "参数异常!";public ParamsException() {super("参数异常!");}public ParamsException(String msg) {super(msg);this.msg = msg;}public ParamsException(Integer code) {super("参数异常!");this.code = code;}public ParamsException(Integer code, String msg) {super(msg);this.code = code;this.msg = msg;}public Integer getCode() {return code;}public void setCode(Integer code) {this.code = code;}public String getMsg() {return msg;}public void setMsg(String msg) {this.msg = msg;}
}

2.6 UserService

java">@Service
public class UserService {@Resourceprivate UserMapper userMapper;/*** 添加⽤户* @param user*/public void saveUser(User user) {AssertUtil.isTrue(StringUtils.isBlank(user.getUserName()), "⽤户名不能为
空!");AssertUtil.isTrue(StringUtils.isBlank(user.getUserPwd()),"⽤户密码不能为
空!");User temp = userMapper.queryUserByUserName(user.getUserName());AssertUtil.isTrue(null != temp, "该⽤户已存在!");AssertUtil.isTrue(userMapper.save(user) < 1,"⽤户记录添加失败!");}
}

2.7 ResultInfo

java">package com.xxxx.springboot.po.vo;
public class ResultInfo {private Integer code = 200;private String msg = "操作成功";private Object result;public Integer getCode() {return code;}public void setCode(Integer code) {this.code = code;}public String getMsg() {return msg;}public void setMsg(String msg) {this.msg = msg;}public Object getResult() {return result;}public void setResult(Object result) {this.result = result;}
}

2.8 UserController

java">@RestController
public class UserController {@Resourceprivate UserService userService;/*** 添加⽤户* @param user* @return*/@PutMapping("user")public ResultInfo saveUser(@RequestBody User user){ResultInfo resultInfo = new ResultInfo();try {userService.saveUser(user);} catch (ParamsException e) {e.printStackTrace();resultInfo.setCode(e.getCode());resultInfo.setMsg(e.getMsg());}catch (Exception e) {e.printStackTrace();resultInfo.setCode(300);resultInfo.setMsg("记录添加失败!");}return resultInfo;}
}

3 修改操作

3.1 接口方法定义

java">public interface UserMapper {// 修改⽤户public int update(User user);
}

3.2 映射文件配置

java"><?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.xxxx.springboot.dao.UserMapper"><update id="update" parameterType="com.xxxx.springboot.po.User">updatetb_usersetuser_name =#{userName},user_pwd=#{userPwd}whereid = #{id}</update>
</mapper>

3.3 UserService

java">@Service
public class UserService {@Resourceprivate UserMapper userMapper;/*** 修改⽤户* @param user*/public void updateUser(User user) {AssertUtil.isTrue(StringUtils.isBlank(user.getUserName()), "⽤户名不能为
空!");AssertUtil.isTrue(StringUtils.isBlank(user.getUserPwd()),"⽤户密码不能为
空!");User temp = userMapper.queryUserByUserName(user.getUserName());AssertUtil.isTrue(null != temp && !
(temp.getId().equals(user.getId())), "该⽤户已存在!");AssertUtil.isTrue(userMapper.update(user) < 1,"⽤户记录添加失败!");}
}

3.4 UserController

java">@RestController
public class UserController {@Resourceprivate UserService userService;/*** 修改⽤户* @param user* @return*/@PostMapping("user")public ResultInfo updateUser(@RequestBody User user){ResultInfo resultInfo = new ResultInfo();try {userService.updateUser(user);} catch (ParamsException e) {e.printStackTrace();resultInfo.setCode(e.getCode());resultInfo.setMsg(e.getMsg());}catch (Exception e) {e.printStackTrace();resultInfo.setCode(300);resultInfo.setMsg("记录更新失败!");}return resultInfo;}
}

4 删除操作

4.1 接口方法定义

java">public interface UserMapper {// 删除⽤户public int deleteUserById(Integer id);
}

4.2 映射文件配置

java"><?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.xxxx.springboot.dao.UserMapper"><delete id="deleteUserById" parameterType="int">delete fromtb_userwhereid=#{id}</delete>
</mapper>

4.3 UserService

java">@Service
public class UserService {@Resourceprivate UserMapper userMapper;/*** 删除⽤户* @param id*/public void deleteUser(Integer id){AssertUtil.isTrue(null == id || null == userMapper.queryById(id),"待删
除记录不存在!");AssertUtil.isTrue(userMapper.deleteUserById(id)<1,"⽤户删除失败!");}
}

4.4 UserController

java">@RestController
public class UserController {@Resourceprivate UserService userService;/*** 删除⽤户* @param userId* @return*/@DeleteMapping("user/{userId}")public ResultInfo deleteUser(@PathVariable Integer userId){ResultInfo resultInfo = new ResultInfo();try {userService.deleteUser(userId);} catch (ParamsException e) {e.printStackTrace();resultInfo.setCode(e.getCode());resultInfo.setMsg(e.getMsg());}catch (Exception e) {e.printStackTrace();resultInfo.setCode(300);resultInfo.setMsg("记录删除失败!");}return resultInfo;}
}

5 分页条件查询操作

5.1 UserQuery

java">package com.xxxx.springboot.query;
public class UserQuery {private Integer pageNum = 1; // 当前⻚private Integer pageSize = 10; // 每⻚显示的数量private String userName; // 查询条件:⽤户名public Integer getPageNum() {return pageNum;}public void setPageNum(Integer pageNum) {this.pageNum = pageNum;}public Integer getPageSize() {return pageSize;}public void setPageSize(Integer pageSize) {this.pageSize = pageSize;}public String getUserName() {return userName;}public void setUserName(String userName) {this.userName = userName;}
}

5.2 接口方法定义

java">public interface UserMapper {// 通过条件,分⻚查询⽤户列表public List<User> selectByParams(UserQuery userQuery);
}

5.3 映射文件配置

java"><?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.xxxx.springboot.dao.UserMapper"><select id="selectByParams"
parameterType="com.xxxx.springboot.query.UserQuery"resultType="com.xxxx.springboot.po.User">select*fromtb_user<where><if test="null != userName and userName !=''">and user_name like concat('%',#{userName},'%')</if></where></select>
</mapper>

5.4 UserService

java">@Service
public class UserService {@Resourceprivate UserMapper userMapper;/*** 通过指定参数,分⻚查询⽤户列表* @param userQuery* @return*/public PageInfo<User> queryUserByParams(UserQuery userQuery){PageHelper.startPage(userQuery.getPageNum(),userQuery.getPageSize());return new PageInfo<User>(userMapper.selectByParams(userQuery));}
}

5.5 UserController

java">@RestController
public class UserController {@Resourceprivate UserService userService;/*** 通过指定参数,分⻚查询⽤户列表* @param userQuery* @return*/@GetMapping("user/list")public PageInfo<User> list(UserQuery userQuery){return userService.queryUserByParams(userQuery);}
}

6 PostMan 工具下载与使用

       在企业 web 应⽤开发中,对服务器端接⼝进⾏测试,通常借助接⼝测试⼯具,这⾥使⽤ Postman 接⼝测试⼯具来对后台 restful 接⼝进⾏测试。

       Postman ⼯具下载地址 :http:// https://www.getpostman.com/apps,选中对应平台下载即可。

       下载安装后,启动 Postman 根据后台接⼝地址发送响应请求即可对接⼝进⾏测试。


http://www.ppmy.cn/server/134064.html

相关文章

【NS3】一、安装

qt - Missing Didn’t find: Qt version 5; install it from packages, or download from https://info.qt.io/download-qt-for-application-development Try: “sudo apt-get install qt5-dev-tools libqt5-dev”, if you have sudo rights. sudo apt-get install qt5-defaul…

实现Shell免密登录的详细指南

实现Shell免密登录的详细指南 前提条件步骤一&#xff1a;生成SSH密钥对步骤二&#xff1a;将公钥复制到远程服务器步骤三&#xff1a;配置SSH客户端&#xff08;可选&#xff09;步骤四&#xff1a;测试免密登录常见问题排查 在使用Linux或Unix系统时&#xff0c;我们经常需要…

强化学习案例:美团是如何在推荐系统中落地强化学习

目录 美团的强化学习应用场景和分析 场景举例 使用原因 强化学习的六大要素 智能体 环境 行动 奖励 目标 状态 美团强化学习模型设计 美团强化学习工程落地 总体的数据结构关系图 实现步骤 1. 日志收集与实时处理&#xff08;Log Collector, Online Joiner&…

无极低码课程【redis windows下服务注册密码修改】

下载Windows版本的Redis linux环境 (自行下载) 1.打开官网https://redis.io/downloads/ windows环境 1.打开github https://github.com/microsoftarchive/redis/releases 然后选择你喜欢的版本zip或msi下载 2.这里下载zip版,解压后后,打开安装目录 3.双击redis-server…

数据抓取时,使用动态IP要注意哪些?

在充满竞争和数据驱动的商业环境中&#xff0c;动态IP已成为数据抓取过程中不可或缺的工具。动态IP的应用能有效提高抓取成功率&#xff0c;但同时也伴随着一系列需要注意的问题。在本文中&#xff0c;我们将详细探讨在数据抓取时使用动态IP时应注意的事项&#xff0c;以确保抓…

深入理解WPF中的数据绑定:完整指南

如果你曾经使用Windows Presentation Foundation (WPF)进行开发&#xff0c;你可能听说过“数据绑定”这个术语。数据绑定是WPF最强大的功能之一&#xff0c;它能够在用户界面和业务逻辑之间实现无缝的数据流&#xff0c;从而简化开发并保持代码整洁。在这篇文章中&#xff0c;…

Java项目-基于Springboot的招生管理系统项目(源码+说明).zip

作者&#xff1a;计算机学长阿伟 开发技术&#xff1a;SpringBoot、SSM、Vue、MySQL、ElementUI等&#xff0c;“文末源码”。 开发运行环境 开发语言&#xff1a;Java数据库&#xff1a;MySQL技术&#xff1a;SpringBoot、Vue、Mybaits Plus、ELementUI工具&#xff1a;IDEA/…

【实战案例】树形字典结构数据的后端解决方案

在管理系统中&#xff0c;经常会有树形结构的数据需求&#xff0c;例如如图所示的课程一级分类和二级分类 对应这样的情况在数据库层面就需要对字段进行设计&#xff0c;表字段信息和示例数据说明如下图所示 通过上述说明可以看出这张表的数据是树形结构&#xff0c;通过根节…