一、前言
前后端分离开发是将项目开发工作前后端交互工作拆分,使前端开发人员能够专注于页面开发或APP 开发,后端开发人员专注与接口开发、业务逻辑开发。
此处开发后端项目,给前端或者APP 端提供接口。不涉及复杂的业务逻辑,通过简单的增删改查来演示后端开发项目。
环境介绍:
- 开发工具:IDEA
- JDK: 1.7 及以上
- Spring Boot: 2.0 及以上
- Maven: 3.0 及以上
二、新建Spring Boot 项目
通过功能菜单File - New - Project 新建Spring Initializr 项目,Project SDK 选择Java 1.8.0,其他默认即可Next 下一步。
图2-1、新建Spring Initializr 项目
坐标Group 填写pers.niaonao,坐标Artifact 填写jdbcproject,项目Name 为jdbcproject,Package 包名为pers.niaonao.jdbcproject。
图2-2、Project Metadata 图
项目依赖选择Web、JDBC、MySQL 然后Next 下一步。
图2-3、选择项目依赖图
图2-4、完成项目创建
你可以另外配置Maven 也可以使用默认的Maven,我这里是自己配置的Maven 3.5
图2-5、Maven 配置图
三、Spring Boot 整合JDBC 与MySQL 交互
3.1 新建数据表skr_user
-- ---------------------------- -- Table structure for skr_user -- ---------------------------- DROP TABLE IF EXISTS `skr_user`; CREATE TABLE `skr_user` ( `id` int(5) NOT NULL AUTO_INCREMENT COMMENT ‘主键‘, `user_id` varchar(20) NOT NULL COMMENT ‘用户ID‘, `user_nick_name` varchar(10) DEFAULT NULL COMMENT ‘用户昵称‘, `user_real_name` varchar(10) DEFAULT NULL COMMENT ‘用户名称‘, `user_phone` varchar(11) DEFAULT NULL, `user_password` varchar(32) DEFAULT NULL, `user_address` varchar(32) DEFAULT NULL, `user_gender` int(1) DEFAULT NULL COMMENT ‘性别: 0/1 - 男/女‘, `user_card` varchar(20) DEFAULT NULL COMMENT ‘身份证‘, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=21 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of skr_user -- ---------------------------- INSERT INTO `skr_user` VALUES (‘1‘, ‘2018072910221899540‘, ‘kecun‘, ‘柯纯‘, ‘15728287364‘, ‘E10ADC3949BA59ABBE56E057F20F883E‘, ‘hpu松7‘, ‘0‘, ‘340824199202010355‘); INSERT INTO `skr_user` VALUES (‘2‘, ‘2018072910221067312‘, ‘huangza‘, ‘皇子昂‘, ‘15746938428‘, ‘E10ADC3949BA59ABBE56E057F20F883E‘, ‘安徽省安庆市潜山县‘, ‘0‘, ‘340824198102115159‘); INSERT INTO `skr_user` VALUES (‘3‘, ‘2018072910221030545‘, ‘guosb‘, ‘郭淑白‘, ‘15647338496‘, ‘E10ADC3949BA59ABBE56E057F20F883E‘, ‘广东省江门市鹤山市‘, ‘1‘, ‘440784198602241121‘); INSERT INTO `skr_user` VALUES (‘4‘, ‘2018072910221012658‘, ‘gongcj‘, ‘龚才俊‘, ‘15746938428‘, ‘E10ADC3949BA59ABBE56E057F20F883E‘, ‘海南省三亚市万宁市‘, ‘0‘, ‘340824199808213429‘); INSERT INTO `skr_user` VALUES (‘5‘, ‘2018072910221060270‘, ‘chenh‘, ‘陈鸿祯‘, ‘13857288463‘, ‘E10ADC3949BA59ABBE56E057F20F883E‘, ‘江苏省淮阴市金湖县‘, ‘0‘, ‘460006197201070474‘); INSERT INTO `skr_user` VALUES (‘6‘, ‘2018072910221209445‘, ‘lie‘, ‘李尔‘, ‘12094847738‘, ‘E10ADC3949BA59ABBE56E057F20F883E‘, ‘河北省邢台市沙河市‘, ‘0‘, ‘513427199812291899‘); INSERT INTO `skr_user` VALUES (‘7‘, ‘2018072910221053415‘, ‘guxz‘, ‘顾兴朝‘, ‘17461937475‘, ‘E10ADC3949BA59ABBE56E057F20F883E‘, ‘西藏自治区日喀则地区‘, ‘0‘, ‘320831199707251836‘); INSERT INTO `skr_user` VALUES (‘8‘, ‘2018072910221052908‘, ‘taohh‘, ‘陶鸿晖‘, ‘11537495365‘, ‘E10ADC3949BA59ABBE56E057F20F883E‘, ‘山西省忻州地区定襄县‘, ‘0‘, ‘130582197910124575‘); INSERT INTO `skr_user` VALUES (‘9‘, ‘2018072910221189175‘, ‘qincc‘, ‘秦痴春‘, ‘15377464838‘, ‘E10ADC3949BA59ABBE56E057F20F883E‘, ‘云南省昆明市呈贡县‘, ‘0‘, ‘142222197709186791‘); INSERT INTO `skr_user` VALUES (‘10‘, ‘2018072910221068870‘, ‘long‘, ‘龙伟兆‘, ‘11827629283‘, ‘E10ADC3949BA59ABBE56E057F20F883E‘, ‘广西壮族自治区南宁市‘, ‘0‘, ‘542300199409116469‘); INSERT INTO `skr_user` VALUES (‘11‘, ‘2018072910221053349‘, ‘qian‘, ‘钱逸明‘, ‘15847562672‘, ‘E10ADC3949BA59ABBE56E057F20F883E‘, ‘陕西省安康地区‘, ‘0‘, ‘530121197909145993‘); INSERT INTO `skr_user` VALUES (‘12‘, ‘2018072910221041169‘, ‘weih‘, ‘韦宏旷‘, ‘18484575399‘, ‘E10ADC3949BA59ABBE56E057F20F883E‘, ‘安徽省安庆市潜山县‘, ‘0‘, ‘45010019710713799X‘); INSERT INTO `skr_user` VALUES (‘13‘, ‘2018072910221654738‘, ‘songms‘, ‘宋妙松‘, ‘18494737626‘, ‘E10ADC3949BA59ABBE56E057F20F883E‘, ‘西藏自治区日喀则地区日喀则市‘, ‘0‘, ‘15212719921025705X‘); INSERT INTO `skr_user` VALUES (‘14‘, ‘2018072910221025795‘, ‘zhanghc‘, ‘张宏畅‘, ‘15122321464‘, ‘E10ADC3949BA59ABBE56E057F20F883E‘, ‘安徽省安庆市枞阳县‘, ‘0‘, ‘612400199301127581‘); INSERT INTO `skr_user` VALUES (‘15‘, ‘2018072910221079179‘, ‘fangxq‘, ‘方新晴‘, ‘15253545293‘, ‘E10ADC3949BA59ABBE56E057F20F883E‘, ‘辽宁省葫芦岛市兴城市‘, ‘1‘, ‘542301199907030111‘); INSERT INTO `skr_user` VALUES (‘16‘, ‘2018072910221091637‘, ‘linz‘, ‘林芷天‘, ‘15847372626‘, ‘E10ADC3949BA59ABBE56E057F20F883E‘, ‘四川省凉山彝族自治州宁南县‘, ‘1‘, ‘21148119971204138X‘); INSERT INTO `skr_user` VALUES (‘17‘, ‘2018072910221022477‘, ‘qianyw‘, ‘钱阳文‘, ‘12828474795‘, ‘E10ADC3949BA59ABBE56E057F20F883E‘, ‘河北省石家庄市赞皇县‘, ‘0‘, ‘513427198007131419‘); INSERT INTO `skr_user` VALUES (‘18‘, ‘2018072910221766265‘, ‘panyq‘, ‘潘雅琴‘, ‘15748237348‘, ‘E10ADC3949BA59ABBE56E057F20F883E‘, ‘河南省濮阳市市区‘, ‘1‘, ‘430412199410027117‘); INSERT INTO `skr_user` VALUES (‘19‘, ‘2018072910221022477‘, ‘hanyh‘, ‘韩宇航‘, ‘12582738394‘, ‘E10ADC3949BA59ABBE56E057F20F883E‘, ‘湖南省衡阳市南岳区‘, ‘0‘, ‘130129198810294762‘); INSERT INTO `skr_user` VALUES (‘20‘, ‘2018072910221066822‘, ‘luth‘, ‘卢天华‘, ‘15943732827‘, ‘E10ADC3949BA59ABBE56E057F20F883E‘, ‘安徽省安庆市潜山县‘, ‘0‘, ‘410902199204160559‘);
3.2 Jdbcproject 项目结构如下
图3-1、项目初始结构图
添加JSON 依赖,pom.xml 文件如下
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>pers.niaonao</groupId> <artifactId>jdbcproject</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>jdbcproject</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.3.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <dependencies> <!--1.JDBC 依赖--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <!--2.Web 依赖--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!--3.MySQL 依赖--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <!--4.JSON依赖--> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.8</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
此处添加了JSON 依赖,前后端数据的传输格式统一为JSON 类型。引入依赖。
图3-2、引入Maven 依赖图
3.3 搭建文件结构
在pers.niaonao.jdbcproject 下新建package 包
- dao: 存放持久层接口
- entity: 存放实体类
- service: 存放业务层相关接口
- util: 存放工具类
- web: 存放Controller 控制层相关类
在资源路径resources 新建application.yml 和application-dev.yml 文件。
- application.yml: 和application.properties 配置文件一样,只是文件格式不一样。Spring Boot 推荐使用yaml 格式配置文件。
- application-dev.yml: 作为开发环境配置文件。(一个项目的开发一般有正式环境application-master.yml,开发环境application-dev.yml,测试环境application-feature.yml)
图3-3、搭建文件结构图
application.xml 文件如下
spring: profiles: active: dev
application-dev.xml 文件如下
#develop environment #端口 server: port: 8082 #数据库 spring: datasource: driver-class-name: com.mysql.jdbc.Driver url: jdbc:mysql://localhost:3306/yonyou_nc username: root password: root
3.4 新建工具类
在util 包下新建加密工具类MD5Util.java,新建id 生成工具类。
加密工具类MD5Util.java
package pers.niaonao.jdbcproject.util; import java.security.MessageDigest; /** * @Author: niaonao * @Date: Created in 15:21 2018/7/29 * @Description :md5加密工具类 */ public class MD5Util { /** * 生成md5 * * @param message * @return */ public static String getMD5(String message) { String md5str = ""; try { // 1 创建一个提供信息摘要算法的对象,初始化为md5算法对象 MessageDigest md = MessageDigest.getInstance("MD5"); // 2 将消息变成byte数组 byte[] input = message.getBytes("UTF-8"); // 3 计算后获得字节数组,这就是那128位了 byte[] buff = md.digest(input); // 4 把数组每一字节(一个字节占八位)换成16进制连成md5字符串 md5str = bytesToHex(buff); } catch (Exception e) { e.printStackTrace(); } return md5str; } /** * 二进制转十六进制 * * @param bytes * @return */ public static String bytesToHex(byte[] bytes) { StringBuffer md5str = new StringBuffer(); // 把数组每一字节换成16进制连成md5字符串 int digital; for (int i = 0; i < bytes.length; i++) { digital = bytes[i]; if (digital < 0) { digital += 256; } if (digital < 16) { md5str.append("0"); } md5str.append(Integer.toHexString(digital)); } return md5str.toString().toLowerCase(); } }
GenerateIdUtil.java
package pers.niaonao.jdbcproject.util; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Random; /** * @Author: niaonao * @Date: Created in 15:21 2018/7/29 * @Desprition: 实体类ID 生成工具类 */ public class GenerateIdUtil { /** 默认用户分表位 */ private static final String DEFAULT_USER_PARTITION = "1"; /** 默认替代位 */ private static final String DEFAULT_REPLACE = "0"; /** 默认横线 */ private static final String DEFAULT_LINE = "-"; /** * 生成 id 方法 * 一般项目会有多个实体类(数据表) * 此处生成id 添加四位标记码可以区分不同的数据表,且能够降低出现重复的id * @param tableBizCode 数据表标记码 * @return */ public static String generateId(String tableBizCode){ //获取当前日期字符串 String dateString = getPartition(new Date()); //获取随机生成十四位数字 String ranString = String.valueOf(new Random().nextLong()).substring(0,6); //如果当前随机数第一位是-,则用0代替 if (ranString.contains(DEFAULT_LINE)){ ranString = ranString.replace(DEFAULT_LINE,DEFAULT_REPLACE); } //iD规则:当前日期字符串 + 1 + 数据表标记码 + 6位随机数字符串 return dateString + DEFAULT_USER_PARTITION + tableBizCode + ranString; } /** * 日期转换 * @param date 当前时间 * @return 日期字符串 */ public static String getPartition(Date date) { //前8位yyyyMMdd格式 DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd"); return dateFormat.format(date); } public static void main(String args[]){ //生成数据格式:2018072910221899540 System.out.println(generateId("0221")); } }
3.5 新建实体类
在entity 包下新建实体类SkrUser.java、RequestEntity.java、ResultEntity.java
数据表对应用户实体类SkrUser.java
package pers.niaonao.jdbcproject.entity; /** * @Author: niaonao * @Date: Created in 16:24 2018/7/29 * @Desprition: 用户实体类 */ public class SkrUser { /** * 用户ID */ private String userId; /** * 用户注册昵称 */ private String userNickName; /** * 用户真实名称 */ private String userRealName; /** * 用户手机号码 */ private String userPhone; /** * 用户登录密码 */ private String userPassword; /** * 用户地址 */ private String userAddress; /** * 用户身份证号 */ private String userCard; /** * 用户性别 * 0/1 - 男/女 */ private int userGender = -1; public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getUserNickName() { return userNickName; } public void setUserNickName(String userNickName) { this.userNickName = userNickName; } public String getUserRealName() { return userRealName; } public void setUserRealName(String userRealName) { this.userRealName = userRealName; } public String getUserPhone() { return userPhone; } public void setUserPhone(String userPhone) { this.userPhone = userPhone; } public String getUserPassword() { return userPassword; } public void setUserPassword(String userPassword) { this.userPassword = userPassword; } public String getUserAddress() { return userAddress; } public void setUserAddress(String userAddress) { this.userAddress = userAddress; } public String getUserCard() { return userCard; } public void setUserCard(String userCard) { this.userCard = userCard; } public int getUserGender() { return userGender; } public void setUserGender(int userGender) { this.userGender = userGender; } }
请求参数封装实体类RequsetEntity.java
package pers.niaonao.jdbcproject.entity; import java.io.Serializable; /** * @Author: niaonao * @Date: Created in 16:36 2018/7/29 * @Desprition: 请求参数封装类 */ public class RequestEntity implements Serializable { private static final long serialVersionUID = 3401781428101852075L; /** * 请求响应数据 */ private String treasureData; public String getTreasureData() { return treasureData; } public void setTreasureData(String treasureData) { this.treasureData = treasureData; } }
后台响应结果封装实体类ResultEntity.java
package pers.niaonao.jdbcproject.entity; import java.io.Serializable; /** * @Author: niaonao * @Date: Created in 16:36 2018/7/29 * @Desprition: 返回结果封装实体类 */ public class ResultEntity implements Serializable { private static final long serialVersionUID = 3401781428101852075L; /** * 接口请求处理结果 * 成功true,失败-false */ private Boolean success; /** * 处理结果信息 */ private String errorMsg; /** * 返回数据对象 */ private Object object; public Boolean getSuccess() { return success; } public void setSuccess(Boolean success) { this.success = success; } public String getErrorMsg() { return errorMsg; } public void setErrorMsg(String errorMsg) { this.errorMsg = errorMsg; } public Object getObject() { return object; } public void setObject(Object object) { this.object = object; } /** * 构造函数 * @param success * @param errorMsg * @param object */ public ResultEntity(Boolean success, String errorMsg, Object object) { this.success = success; this.errorMsg = errorMsg; this.object = object; } }
3.6 完善持久层和业务层代码
新建持久层接口SkrUserDao.java
package pers.niaonao.jdbcproject.dao; import pers.niaonao.jdbcproject.entity.SkrUser; import java.util.List; /** * @Author: niaonao * @Date: Created in 16:25 2018/7/29 * @Desprition: 用户持久层接口类 */ public interface SkrUserDao { /** * 多条件查询获取实体信息 * @param SkrUser * @return */ SkrUser selectByParams(SkrUser SkrUser); /** * 获取全部用户 * @param SkrUser * @return */ List<SkrUser> getList(SkrUser SkrUser); /** * 更新用户信息(如果字段不为空更新) * @param SkrUser * @return */ int updateByIdSelective(SkrUser SkrUser); /** * 根据id删除实体信息 * @param SkrUser * @return */ int deleteById(SkrUser SkrUser); /** * 插入用户记录 * @param SkrUser * @return */ int insert(SkrUser SkrUser); /** * 根据不为空的参数插入用户记录 * @param SkrUser * @return */ int insertBySelective(SkrUser SkrUser); }
在包pers.niaonao.jdbcproject.dao 下新建package 包 daoimpl
在daoimpl 下新建实现类SkrUserDaoImpl.java
package pers.niaonao.jdbcproject.dao.daoimpl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Repository; import pers.niaonao.jdbcproject.dao.SkrUserDao; import pers.niaonao.jdbcproject.entity.SkrUser; import pers.niaonao.jdbcproject.util.MD5Util; import java.util.List; /** * @Author: niaonao * @Date: Created in 16:29 2018/7/29 * @Desprition: 用户持久层接口实现类 */ @Repository public class SkrUserDaoImpl implements SkrUserDao { @Autowired private JdbcTemplate jdbcTemplate; @Override public SkrUser selectByParams(SkrUser skrUser) { //拼接多条件查询语句,支持模糊查询 String sql = " select user_id, user_nick_name, user_password, user_real_name," + " user_gender, user_card, user_phone, user_address from skr_user WHERE "; if (skrUser.getUserId() != null){ sql = sql + " user_id = ‘" + skrUser.getUserId() + "‘ AND "; } if (skrUser.getUserRealName() != null) { sql = sql + " user_real_name = ‘" + skrUser.getUserRealName() + "‘ AND "; } if (skrUser.getUserNickName() != null){ sql = sql + " user_nick_name = ‘" + skrUser.getUserNickName() + "‘ AND "; } if (skrUser.getUserPassword() != null){ sql = sql + " user_password = ‘" + MD5Util.getMD5(skrUser.getUserPassword()) + "‘ AND "; } if (skrUser.getUserPassword() != null){ sql = sql + " user_phone = ‘" + skrUser.getUserPhone() + "‘ AND "; } if (skrUser.getUserPassword() != null){ sql = sql + " user_gender = ‘" + skrUser.getUserGender() + "‘ AND "; } if (skrUser.getUserPassword() != null){ sql = sql + " user_address = ‘" + skrUser.getUserAddress() + "‘ AND "; } //截取SQl语句多余后缀 if (sql.endsWith("AND ")){ sql = sql.substring(0,sql.length() - 4); } //封装执行SQL 语句结果 List<SkrUser> skrUserList = jdbcTemplate.query(sql ,new Object[]{}, new BeanPropertyRowMapper(SkrUser.class)) ; if (skrUserList == null || skrUserList.size() < 1){ return null; } return skrUserList.get(0); } @Override public List<SkrUser> getList(SkrUser skrUser) { //拼接SQL语句 String sql = " SELECT user_id, user_nick_name, user_password, user_real_name," + " user_gender, user_card, user_phone, user_address FROM skr_user WHERE "; if (skrUser.getUserId() != null){ sql = sql + " user_id = ‘" + skrUser.getUserId() + "‘ AND "; } if (skrUser.getUserRealName() != null) { sql = sql + " user_real_name LIKE ‘%" + skrUser.getUserRealName() + "%‘ AND "; } if (skrUser.getUserNickName() != null){ sql = sql + " user_nick_name LIKE ‘%" + skrUser.getUserNickName() + "%‘ AND "; } if (skrUser.getUserPassword() != null){ sql = sql + " user_password LIKE ‘%" + MD5Util.getMD5(skrUser.getUserPassword()) + "%‘ AND "; } if (skrUser.getUserPhone() != null){ sql = sql + " user_phone LIKE ‘%" + skrUser.getUserPhone() + "%‘ AND "; } if (skrUser.getUserGender() == 1 || skrUser.getUserGender() == 0){ sql = sql + " user_gender LIKE ‘%" + skrUser.getUserGender() + "%‘ AND "; } if (skrUser.getUserAddress() != null){ sql = sql + " user_address LIKE ‘%" + skrUser.getUserAddress() + "%‘ AND "; } //截取SQl语句多余后缀 if (sql.endsWith("WHERE ")){ sql = sql.substring(0,sql.length() - 6); }else if (sql.endsWith("AND ")){ sql = sql.substring(0,sql.length() - 4); } return jdbcTemplate.query(sql, new Object[]{}, new BeanPropertyRowMapper(SkrUser.class)); } @Override public int updateByIdSelective(SkrUser skrUser) { //根据对象唯一ID更新 if (skrUser.getUserId() == null){ return 0; } //拼接SQL语句,拼接SQL语句考虑拼接的数据加单引号 String sql = "UPDATE skr_user SET " ; if (skrUser.getUserRealName() != null) { sql = sql + " user_real_name = ‘" + skrUser.getUserRealName() + "‘ , "; } if (skrUser.getUserNickName() != null) { sql = sql + " user_nick_name = ‘" + skrUser.getUserNickName() + "‘ , "; } if (skrUser.getUserPassword() != null) { sql = sql + " user_password = ‘" + skrUser.getUserPassword() + "‘ , "; } if (skrUser.getUserAddress() != null) { sql = sql + " user_address = ‘" + skrUser.getUserAddress() + "‘ , "; } if (skrUser.getUserGender() == 1 || skrUser.getUserGender() == 0) { sql = sql + " user_gender = ‘" + skrUser.getUserGender() + "‘ , "; } if (skrUser.getUserCard() != null) { sql = sql + " user_card = ‘" + skrUser.getUserCard() + "‘ , "; } if (skrUser.getUserPhone() != null) { sql = sql + " user_phone = ‘" + skrUser.getUserPhone() + "‘ , "; } if (sql.endsWith("SET")){ return 0; } //截取SQl语句多余后缀","并拼接WHERE条件 if (sql.endsWith(", ")){ sql = sql.substring(0,sql.length() - 2) + " WHERE user_id = ‘" + skrUser.getUserId() + "‘"; } return jdbcTemplate.update(sql); } @Override public int deleteById(SkrUser skrUser) { //根据对象唯一ID删除 if (skrUser.getUserId() == null){ return 0; } return jdbcTemplate.update("DELETE from skr_user WHERE user_id=?",skrUser.getUserId()); } @Override public int insert(SkrUser skrUser) { String sql = "INSERT INTO skr_user " + "(user_id, user_nick_name, user_password, user_address, user_real_name, user_gender, user_card, user_phone)" + " VALUES (?,?,?,?,?,?,?,?)"; return jdbcTemplate.update(sql, skrUser.getUserId(), skrUser.getUserNickName(), skrUser.getUserPassword(), skrUser.getUserAddress(),skrUser.getUserRealName(),skrUser.getUserGender(),skrUser.getUserCard(),skrUser.getUserPhone()); } @Override public int insertBySelective(SkrUser skrUser) { skrUser.setUserRealName(skrUser.getUserRealName() == null ? "" : skrUser.getUserRealName()); skrUser.setUserNickName(skrUser.getUserNickName() == null ? "" : skrUser.getUserNickName()); skrUser.setUserPassword(skrUser.getUserPassword() == null ? "" : skrUser.getUserPassword()); skrUser.setUserNickName(skrUser.getUserNickName() == null ? "" : skrUser.getUserNickName()); skrUser.setUserAddress(skrUser.getUserAddress() == null ? "" : skrUser.getUserAddress()); skrUser.setUserCard(skrUser.getUserCard() == null ? "" : skrUser.getUserCard()); skrUser.setUserGender(skrUser.getUserGender()); skrUser.setUserId(skrUser.getUserId()); String sql = "INSERT INTO skr_user " + "(user_id, user_nick_name, user_password, user_address, user_real_name, user_gender, user_card, user_phone)" + " VALUES (?,?,?,?,?,?,?,?)"; return jdbcTemplate.update(sql, skrUser.getUserId(), skrUser.getUserNickName(), skrUser.getUserPassword(), skrUser.getUserAddress(),skrUser.getUserRealName(),skrUser.getUserGender(),skrUser.getUserCard(),skrUser.getUserPhone()); } }
在包service 下新建业务接口SkrUserService.java
package pers.niaonao.jdbcproject.service; import pers.niaonao.jdbcproject.entity.RequestEntity; import pers.niaonao.jdbcproject.entity.ResultEntity; /** * @Author: niaonao * @Date: Created in 16:26 2018/7/29 * @Desprition: 用户业务接口 */ public interface SkrUserService { /** * 多条件获取用户 * @param requestEntity * @return */ ResultEntity getSkrUser(RequestEntity requestEntity); /** * 获取全部用户 * @param requestEntity * @return */ ResultEntity getSkrUserList(RequestEntity requestEntity); /** * 更新用户信息(如果字段不为空更新) * @param requestEntity * @return */ ResultEntity updateSkrUser(RequestEntity requestEntity); /** * 根据id删除用户信息 * @param requestEntity * @return */ ResultEntity deleteSkrUser(RequestEntity requestEntity); /** * 注册用户 * @param requestEntity * @return */ ResultEntity addSkrUser(RequestEntity requestEntity); }
在pers.niaonao.jdbcproject.service 下新建package 包serviceimpl
在serviceimpl 下新建业务实现类SkrUserServiceImpl.java
package pers.niaonao.jdbcproject.service.serviceimpl; import com.alibaba.fastjson.JSONObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import pers.niaonao.jdbcproject.dao.SkrUserDao; import pers.niaonao.jdbcproject.entity.RequestEntity; import pers.niaonao.jdbcproject.entity.ResultEntity; import pers.niaonao.jdbcproject.entity.SkrUser; import pers.niaonao.jdbcproject.service.SkrUserService; import pers.niaonao.jdbcproject.util.GenerateIdUtil; import pers.niaonao.jdbcproject.util.MD5Util; import java.util.List; /** * @Author: niaonao * @Date: Created in 16:29 2018/7/29 * @Desprition: 用户业务实现类 */ @Service public class SkrUserServiceImpl implements SkrUserService { @Autowired private SkrUserDao skrUserDao; @Override public ResultEntity getSkrUser(RequestEntity requestEntity) { //解析请求数据 SkrUser user = JSONObject.parseObject(requestEntity.getTreasureData(), SkrUser.class); Boolean success = Boolean.FALSE; String errorMsg = "获取用户信息成功!"; if (user == null){ errorMsg = "请求数据不能为空!"; } else { //根据请求参数查询用户信息 user = skrUserDao.selectByParams(user); if (user == null){ errorMsg = "用户信息不存在!"; } else { success = Boolean.TRUE; } } //封装返回结果 ResultEntity resultEntity = new ResultEntity(success,errorMsg,user); return resultEntity; } @Override public ResultEntity getSkrUserList(RequestEntity requestEntity) { //解析请求数据 SkrUser user = JSONObject.parseObject(requestEntity.getTreasureData(), SkrUser.class); if (user == null){ user = new SkrUser(); } //获取用户信息集合 List<SkrUser> userList = skrUserDao.getList(user); //初始化执行结果 Boolean success = Boolean.TRUE; String errorMsg = "获取用户信息成功!"; if (userList == null) { success = Boolean.FALSE; errorMsg = "用户信息不存在!!"; } //封装返回结果 ResultEntity resultEntity = new ResultEntity(success,errorMsg,userList); return resultEntity; } @Override public ResultEntity updateSkrUser(RequestEntity requestEntity) { //解析请求数据 SkrUser user = JSONObject.parseObject(requestEntity.getTreasureData(), SkrUser.class); Boolean success = Boolean.FALSE; String errorMsg = "更新用户信息成功!"; if (user == null){ errorMsg = "请求数据不能为空!"; } else if (user.getUserId() == null || user.getUserId().equals("")){ errorMsg = "用户编号不能为空!"; } else { //更新用户信息 int resultRow = skrUserDao.updateByIdSelective(user); if (resultRow < 1){ errorMsg = "更新用户失败!"; }else { success = Boolean.TRUE; } } //封装返回结果 ResultEntity resultEntity = new ResultEntity(success, errorMsg, null); return resultEntity; } @Override public ResultEntity deleteSkrUser(RequestEntity requestEntity) { //解析请求数据 SkrUser user = JSONObject.parseObject(requestEntity.getTreasureData(), SkrUser.class); Boolean success = Boolean.FALSE; String errorMsg = "用户删除成功!"; if (user == null){ errorMsg = "请求数据不能为空!"; } else if (user.getUserId() == null || user.getUserId().equals("")){ errorMsg = "用户编号不能为空!"; } else { //删除用户信息 int resultRow = skrUserDao.deleteById(user); if (resultRow < 1){ errorMsg = "删除用户失败!"; }else { success = Boolean.TRUE; } } //封装返回结果 ResultEntity resultEntity = new ResultEntity(success, errorMsg, null); return resultEntity; } @Override public ResultEntity addSkrUser(RequestEntity requestEntity) { //解析请求数据 SkrUser user = JSONObject.parseObject(requestEntity.getTreasureData(), SkrUser.class); Boolean success = Boolean.FALSE; String errorMsg = "添加用户成功!"; if (user == null){ errorMsg = "请求数据不能为空!"; } else if (user.getUserNickName() == null || user.getUserPassword() == null || user.getUserNickName().equals("") || user.getUserPassword().equals("")){ errorMsg = "用户名和密码不能为空!"; } else { //生成id,此处参数自定义,作为数据表标识。此处以1234 标识skr_user user.setUserId(GenerateIdUtil.generateId("1234")); //登录密码加密 user.setUserPassword(MD5Util.getMD5(user.getUserPassword())); //插入用户信息 int resultRow = skrUserDao.insertBySelective(user); if (resultRow < 1){ errorMsg = "添加用户失败!"; }else { success = Boolean.TRUE; } } //封装返回结果 ResultEntity resultEntity = new ResultEntity(success, errorMsg, null); return resultEntity; } }
至此基本的业务逻辑和数据库交互开发完成。
四、后端项目对外接口开发
后端项目通过控制层Controller 来处理前端发出的请求。在控制层调用业务层Service ,具体的业务逻辑代码编写工作在业务层实现。
此处在包web 下新建用户控制类AppUserController.java 来响应前端请求。
package pers.niaonao.jdbcproject.web; import org.springframework.web.bind.annotation.*; import pers.niaonao.jdbcproject.entity.RequestEntity; import pers.niaonao.jdbcproject.entity.ResultEntity; import pers.niaonao.jdbcproject.service.SkrUserService; import javax.annotation.Resource; /** * @Author: niaonao * @Date: Created in 16:27 2018/7/29 * @Desprition: 前端访问接口的控制类 */ @RestController @RequestMapping(value = "/app") public class AppUserController { @Resource private SkrUserService skrUserService; /** * 获取用户信息列表 * 多条件模糊查询 * @return */ @ResponseBody @PostMapping(value = "/user/getAllSkrUser", produces ="application/json;charset=UTF-8" ) public ResultEntity getSkrUserList(@RequestBody RequestEntity requestEntity) { return skrUserService.getSkrUserList(requestEntity); } /** * 获取用户 * @param requestEntity * @return */ @ResponseBody @PostMapping(value = "/user/getSkrUser", produces ="application/json;charset=UTF-8" ) public ResultEntity getSkrUser(@RequestBody RequestEntity requestEntity) { return skrUserService.getSkrUser(requestEntity); } /** * 更新用户 * @param requestEntity * @return */ @ResponseBody @PostMapping(value = "/user/updateSkrUser", produces ="application/json;charset=UTF-8" ) public ResultEntity updateSkrUser(@RequestBody RequestEntity requestEntity) { return skrUserService.updateSkrUser(requestEntity); } /** * 注册用户 * @param requestEntity * @return */ @ResponseBody @PostMapping(value = "/user/registerSkrUser", produces ="application/json;charset=UTF-8" ) public ResultEntity addSkrUser(@RequestBody RequestEntity requestEntity) { return skrUserService.addSkrUser(requestEntity); } /** * 删除用户 * @param requestEntity * @return */ @ResponseBody @PostMapping(value = "/user/deleteSkrUser", produces ="application/json;charset=UTF-8" ) public ResultEntity deleteSkrUser(@RequestBody RequestEntity requestEntity) { return skrUserService.deleteSkrUser(requestEntity); } }
项目最终结构图如下:
图4-1、项目完成结构图
五、后端开发项目测试
此处使用接口测试工具Postman 进行测试项目JdbcProject。快捷键Shift + Alt + D 运行项目。打开Postman 新建测试数据测试截图如下。以上五个接口均已测试通过。以注册用户接口为例。
- 项目运行端口8082
- 请求方式为Post
- 请求数据类型为JSON 类型
测试请求数据格式如下:
{ "treasureData":"{\"userPassword\":\"yixiaochuan\",\"userNickName\":\"lvsu\",\"userRealName\":\"吕素\",\"userAddress\":\"秦朝单父县\",\"userGender\":\"1\"}" }
图5-1、用户注册测试图
原文地址:https://www.cnblogs.com/niaonao/p/9386705.html