美文网首页美文共赏
Spring Boot实现增删改查接口

Spring Boot实现增删改查接口

作者: 放羊娃华振 | 来源:发表于2021-12-11 15:20 被阅读0次

    一、概述

    最近觉得写Android太无聊了,就简单研究加后端框架吧。

    二、环境准备

    本次就不描述如何去创建Spring工程了,直接实现真实的注册登录操作。当然这只是个demo很多逻辑不够健全的地方就不做细纠了,毕竟精力有限。
    1.mysql环境
    2.navicat工具
    3.maven环境

    三、代码实现

    由于代码中很多面向接口编程的,我就不放接口代码了,就只具具体的实现的代码,另外数据库的操作也有很多种,我就尽量使用少引入框架的方式。
    1.controller实现.里面有些参数的含义可以参考:https://blog.csdn.net/zhangpower1993/article/details/81878773

    package com.stormdzh.study.springdemo.controller.user;
    
    import com.stormdzh.study.springdemo.service.user.impl.UserServiceImpl;
    import com.stormdzh.study.springdemo.utils.common.rest.RestResponse;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.bind.annotation.RestController;
    
    import java.util.Map;
    
    /**
     * 参数解析:
     * uid
     * nane
     * psw
     */
    
    @RestController
    @RequestMapping(value = "/user")
    public class UserController {
    
        @Autowired
        private UserServiceImpl userService;
    
        /**
         * 注册接口
         *
         * @param params
         * @return
         */
        @RequestMapping(value = "/register")
        public Object register(@RequestParam Map<String, String> params) {
            Object register = userService.register(params);
            if(register == null) {
                return RestResponse.success(register);
            }else{
                return RestResponse.error("用户已存在!");
            }
        }
    
        /**
         * 登录接口
         *
         * @param params
         * @return
         */
        @RequestMapping(value = "/login")
        public Object login(@RequestParam Map<String, String> params) {
            Object login = userService.login(params);
            if (login == null) {
                return RestResponse.error("登录失败!");
            } else {
                return RestResponse.success(login);
            }
        }
    
        /**
         * 登出接口
         *
         * @param params
         * @return
         */
        @RequestMapping(value = "/logout")
        public Object logout(@RequestParam Map<String, String> params) {
            return RestResponse.success(userService.logout(params));
        }
    
    }
    
    

    2.service的实现

    package com.stormdzh.study.springdemo.service.user.impl;
    
    import com.stormdzh.study.springdemo.bean.user.db.DUser;
    import com.stormdzh.study.springdemo.dao.user.impl.UserDaoImpl;
    import com.stormdzh.study.springdemo.service.user.UserService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Component;
    
    import java.util.Map;
    
    @Component
    public class UserServiceImpl implements UserService {
    
        @Autowired
        private UserDaoImpl userDao;
    
        @Override
        public Object register(Map<String, String> params) {
            DUser user = userDao.query(params);
            if (user == null) {
                userDao.insert(params);
            } else {//用户已经存在
    
            }
            return user;
        }
    
        @Override
        public Object login(Map<String, String> params) {
            DUser user = userDao.query(params);
            if (user != null && user.getUname().equals(params.get("name")) && user.getUpsw().equals(params.get("psw"))) {
                return user;
            }
            return null;
        }
    
        @Override
        public Object logout(Map<String, String> params) {
            userDao.update(params);
            DUser user = userDao.query(params);
            return user;
        }
    }
    
    

    3.dao数据访问层的实现

    package com.stormdzh.study.springdemo.dao.user.impl;
    
    import com.stormdzh.study.springdemo.bean.user.db.DUser;
    import com.stormdzh.study.springdemo.dao.user.UserDao;
    import com.stormdzh.study.springdemo.dao.user.mapper.UsersRowMapper;
    import com.stormdzh.study.springdemo.utils.common.AppUtils;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.jdbc.core.JdbcTemplate;
    import org.springframework.jdbc.core.PreparedStatementCreator;
    import org.springframework.stereotype.Component;
    
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.SQLException;
    import java.util.List;
    import java.util.Map;
    import java.util.Set;
    
    /**
     * 默认条件是userid
     */
    @Component
    public class UserDaoImpl implements UserDao {
    
        public String TABLE_NAME = "tb_users";
    
        @Autowired
        JdbcTemplate jdbcTemplate;
    
    
        @Override
        public void insert(Map<String, String> params) {
            jdbcTemplate.update(new PreparedStatementCreator() {
    
                @Override
                public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
                    String sql = "insert into " + TABLE_NAME + " (uid,uname,upsw) values(?,?,?)";
                    PreparedStatement ps = con.prepareStatement(sql);
                    ps.setString(1, params.get("uid"));
                    ps.setString(2, params.get("name"));
                    ps.setString(3, params.get("psw"));
                    return ps;
                }
            });
    
    
        }
    
        @Override
        public void delete(Map<String, String> params) {
            String sql = "DELETE FROM " + TABLE_NAME + " WHERE uname = " + "'" + params.get("name") + "'";
            jdbcTemplate.execute(sql);
        }
    
        @Override
        public void update(Map<String, String> params) {
            String whereStr = "";
            String uid = params.get("uid");
            String uname = params.get("uname");
            if (!AppUtils.isTextEmpty(uid)) {
                whereStr = "uid = " + uid;
            } else if (!AppUtils.isTextEmpty(uname)) {
                whereStr = "uname = '" + uname + "'";
            }
    
            Set<Map.Entry<String, String>> entrySet = params.entrySet();
            String updateStr = "";
            for (Map.Entry<String, String> entry : entrySet) {
                String key = entry.getKey();
                String value = entry.getValue();
                if (!AppUtils.isTextEmpty(updateStr))
                    updateStr = updateStr + " , ";
                updateStr = updateStr + key + "='" + value + "'";
            }
            if (AppUtils.isTextEmpty(updateStr))
                return;
    
            String sql = "update " + TABLE_NAME + " set " + updateStr + " where " + whereStr;
            System.out.println("updateUser==>" + sql);
    
            jdbcTemplate.execute(sql);
        }
    
        @Override
        public DUser query(Map<String, String> params) {
            String sql = "SELECT * FROM " + TABLE_NAME + " WHERE uname = " + "'" + params.get("name") + "'";
            List<DUser> userList = jdbcTemplate.query(sql, new UsersRowMapper());
            if (AppUtils.isEmptyColls(userList)) {
                return null;
            }
            return userList.get(0);
        }
    }
    
    

    4.数据库的依赖以及配置

    #数据库配置
    spring.datasource.url=jdbc:mysql://127.0.0.1:3306/gkkt?useUnicode=true&useJDBCCompliantTimezoneShift=true&serverTimezone=UTC&characterEncoding=utf8
    spring.datasource.username=root
    spring.datasource.password=12345678
    spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
    # 下面方法已经过时
    # spring.datasource.driver-class-name=com.mysql.jdbc.Driver
    
    
            #数据库依赖
            <!-- 链接mysql -->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
            </dependency>
    
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-jdbc</artifactId>
            </dependency>
    

    四、效果

    1.发送注册请求:http://localhost:8080/user/register?name=user1&psw=123,接口和数据都ok。

    image.png
    image.png
    2.发送登录请求:http://localhost:8080/user/login?name=user1&psw=123,调用ok。
    image.png

    相关文章

      网友评论

        本文标题:Spring Boot实现增删改查接口

        本文链接:https://www.haomeiwen.com/subject/enrkfrtx.html