Springboot+html5+mysql的CRUD增删改查(基础版本详细,附带源码)(二)

本文涉及的产品
云数据库 RDS MySQL Serverless,0.5-2RCU 50GB
云数据库 RDS MySQL Serverless,价值2615元额度,1个月
简介: Springboot+html5+mysql的CRUD增删改查(基础版本详细,附带源码)(二)

Serviceimpl 实现层

package com.example.demo.service.impl;
import com.example.demo.entity.UserEntity;
import com.example.demo.mapper.UserinfoMapper;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service  //。@Service用于标注业务层组件
public class UserinfoServiceImpl implements UserService {
  //引入dao接口
    @Autowired
    private UserinfoMapper userinfoMapper;
    /**
     * 调用finall 实现查询全部
     * @return
     */
    @Override
    public List<UserEntity> findall() {
        return userinfoMapper.findall();
    }
    /**
     * 调用getselectId 实现根据id查询
     * @param id
     * @return
     */
    @Override
    public UserEntity getselectId(int id) {
        return userinfoMapper.getselectId(id);
    }
    /**
     * 根据id 删除对应的数据
     * @param id
     * @return
     */
    @Override
    public int delectId(int id) {
        return userinfoMapper.delectId(id);
    }
    /**
     * 新增数据
     * @param userEntity
     * @return
     */
    @Override
    public int addall(UserEntity userEntity) {
        return userinfoMapper.addall(userEntity);
    }
    /**
     * 修改数据 根据id
     * @param userEntity
     * @return
     */
    @Override
    public int update(UserEntity userEntity) {
        return userinfoMapper.update(userEntity);
    }
}


Dao的接口层

package com.example.demo.mapper;
import com.example.demo.entity.UserEntity;
import java.util.List;
public interface UserinfoMapper {
    /**
     * 查询全部
     * @return
     */
    List<UserEntity> findall();
    /**
     * 根据id查询
     * @param id
     * @return
     */
    UserEntity getselectId(int id);
    /**
     * 根据id删除
     * @param id
     * @return
     */
    int delectId(int id);
    /**
     * 新增数据
     * @param userEntity
     * @return
     */
    int addall(UserEntity userEntity);
    /**
     * 修改数据id
     * @param userEntity
     * @return
     */
    int update(UserEntity userEntity);
}


启动类: 你们用自己默认的就行 我发出来是 怕你们手写的不会写

package com.example.demo;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan(basePackages = "com.example.demo.mapper")
public class DemoApplication {
  public static void main(String[] args) {
  SpringApplication.run(DemoApplication.class, args);
  }
}


Mapper 层 sql 代码

<?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">
    <!--数据源文件(告知程序着是数据源从这里拿数据Repository)-->
    <mapper namespace="com.example.demo.mapper.UserinfoMapper">
    <resultMap id="userMap" type="com.example.demo.entity.UserEntity">
        <id column="id" property="id" jdbcType="INTEGER"/>
        <result column="name" property="name"/>
        <result column="login" property="login"/>
        <result column="password" property="password"/>
    </resultMap>
<!--    把一些数据都在一起 调用的时候直接写Man_sql_name 即可-->
    <sql id="Man_sql_name">
        id,name,login,password
    </sql>
<!--     查询全部信息-->
    <select id="findall"  parameterType="com.example.demo.entity.UserEntity" resultMap="userMap">
        select
        <include refid="Man_sql_name"/>
        from user
    </select>
<!--     根据id查询数据-->
    <select id="getselectId"  parameterType="integer" resultMap="userMap">
        select
        <include refid="Man_sql_name"/>
        from user where id=#{id}
    </select>
    <!--     根据id删除数据-->
    <delete id="delectId"  parameterType="int">
        delete
        from user where id=#{id}
    </delete>
<!--     新增数据-->
    <insert id="addall"  parameterType="com.example.demo.entity.UserEntity">
        insert into user
<trim prefix="(" suffix=")" suffixOverrides="," >
        <if test="id != null" >
            id,
        </if>
        <if test="name != null" >
            name,
        </if>
        <if test="login != null" >
            login,
        </if>
        <if test="password != null" >
            password,
        </if>
    </trim>
        <trim prefix="values (" suffix=")" suffixOverrides="," >
        <if test="id != null" >
            #{id,jdbcType=VARCHAR},
        </if>
        <if test="name != null" >
            #{name,jdbcType=VARCHAR},
        </if>
         <if test="login != null" >
                #{login,jdbcType=VARCHAR},
          </if>
        <if test="password != null" >
            #{password,jdbcType=VARCHAR},
        </if>
        </trim>
    </insert>
<!--  修改数据-->
    <update id="update" parameterType="com.example.demo.entity.UserEntity">
        update  user
        <set>
        <if test="name !=null">
            name =#{name,jdbcType=VARCHAR},
        </if>
        <if test="login !=null">
            login=#{login,jdbcType=VARCHAR},
        </if>
        <if test="password !=null">
            password=#{password,jdbcType=VARCHAR},
        </if>
        </set>
        where id=#{id,jdbcType=VARCHAR}
    </update>
</mapper>


第一部分的代码就结束了


展示部分页面实现效果:


查询全部


http://localhost:1234/user/list

其它的感兴趣的同学自己去操作吧我就不一一操作了


下面介绍第二部分 页面的CRUD


后端只有控制台不一样其他的都是一样的


Controllrt

package com.example.demo.controller;
import com.example.demo.entity.UserEntity;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import java.util.Collection;
@Controller
public class HtmlController {
//todo    ====================================页面调用---》  http://localhost:1234/emps
    @Autowired
    private UserService userService;
    /**
     *
     * //他的,@GetMapping是一个组合注解,是@RequestMapping(method = RequestMethod.GET)的缩写。
     * @param model
     * @return
     * http://localhost:1234/emps
     */
    @GetMapping("/emps")
    public String getEmps(Model model){
        Collection<UserEntity> entities =userService.findall();
        //放入域中
          model.addAttribute("entities",entities);
        System.out.println("entities//=="+entities);
        // thymeleaf默认就会拼串
        // classpath:/templates/xxxx.html
        return "index";
      //  return new ModelAndView("index");
    }
    //删除员工
    @RequestMapping (value = "/delect/{id}",method = RequestMethod.POST)
    public String deleteEmp(@PathVariable("id") Integer id) {
        //根据id删除员工
        userService.delectId(id);
        //删除后返回本页面 主页
        return "redirect:/emps";
    }
/**
 *
 */
    //回显页面
    @RequestMapping (value = "/selectUp/{id}")
    public String selectUp(@PathVariable("id") Integer id,Model model) {
        UserEntity userEntity = userService.getselectId(id);
        System.out.println("进来了update"+userEntity);
        model.addAttribute("userEntity",userEntity);
        //删除后返回本页面 主页
        return "update";
    }
    /**
     *  修改
     * @param userEntity
     * @return
     *
     * http://localhost:1234/user/updatess
     */
    @RequestMapping("/updatehtml")
    public String Upate(UserEntity userEntity){
        int results=userService.update(userEntity);
        if(results==1){
            System.out.println("更新成功");
        }else {
            System.out.println("更新失败");
        }
        return "index";
    }
}


页面代码


index.html

<!DOCTYPE html>
<!--<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">-->
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <!-- 以下方式定时转到其他页面 -->
<!--    <meta http-equiv="refresh" content="5;url=add.html">-->
</head>
<!--  springboot-->
<script src="/js/jquery.min.js"></script>
<script type="text/javascript" src="/js/jquery.easyui.min.js"></script>
<body>
<table border="1" style="border-collapse: collapse;">
    <caption>基本的联系</caption>
    <thead>
    <tr>
        <th>id</th>
        <th>名字</th>
        <th>登录账号</th>
        <th>密码</th>
    </tr>
    </thead>
   <tbody>
     <tr th:each="user:${entities}">
         <th th:text="${user.id}">id</th>
         <th th:text="${user.name}">name</th>
         <th th:text="${user.login}">login</th>
         <th th:text="${user.password}">password</th>
         <th>
             <a class="btn btn-sm btn-primary" th:href="@{/selectUp/}+${user.id}">编辑</a>
             <button th:attr="delete_uri=@{/delect/}+${user.id}" class="btn btn-sm btn-danger deleteBtn">删除</button>
         </th>
     </tr>
   </tbody>
</table>
<!--定义一个form表单,发送delete请求-->
<form id="deleteEmpForm" method="post">
    <input type="hidden" name="_method" value="DELETE">
</form>
<!--定义js方法,当点击删除按钮时,删除员工信息-->
<script>
    $(".deleteBtn").click(function(){
        //删除当前员工
        $("#deleteEmpForm").attr("action", $(this).attr("delete_uri")).submit();//action指定执行方法请求路径
        return false;
    })
</script>
<div>
  <div>================</div>
    <a  href = "/user/ahtml">
        <button>新增</button >
    </a>
</div>
</body>
</html>


add.html 新增代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>新增页面</title>
</head>
<body>
 <form method="post" onsubmit="return false" action="##" id="add">
     id:<input type="text" name="id"><br>
     name:<input type="text" name="name"><br>
     login:<input type="text" name="login"><br>
     password:<input type="password" name="password"><br>
     <input type="button" value="新增" onclick="loginsa()">
 </form>
<!--      html页面可用-->
<!--        <script type="text/javascript" src="../static/js/jquery.min.js"></script>-->
<!--         <script type="text/javascript" src="../static/js/jquery.easyui.min.js"></script>-->
<!--  springboot-->
 <script src="/js/jquery.min.js"></script>
 <script type="text/javascript" src="/js/jquery.easyui.min.js"></script>
<script type="text/javascript">
    function loginsa(){
    $.ajax({
        type:"POST",//方法类型
        dataType: "text",//预期服务器返回的数据类型 如果是对象返回的是json 如果是字符串这里一定要定义text 之前我就是定义json 结果字符串的返回一直到额error中去
    /*
    dataType:
        要求为String类型的参数,预期服务器返回的数据类型。如果不指定,JQuery将自动根据http包mime信息返回responseXML或responseText,并作为回调函数参数传递。可用的类型如下:
        xml:返回XML文档,可用JQuery处理。
        html:返回纯文本HTML信息;包含的script标签会在插入DOM时执行。
        script:返回纯文本JavaScript代码。不会自动缓存结果。除非设置了cache参数。注意在远程请求时(不在同一个域下),所有post请求都将转为get请求。
        json:返回JSON数据。
        jsonp:JSONP格式。使用SONP形式调用函数时,例如myurl?callback=?,JQuery将自动替换后一个“?”为正确的函数名,以执行回调函数。
        text:返回纯文本字符串。
    */
        url:"/user/adds",
        data:$('#add').serialize(),
        success: function (result) {
            alert("成功")
            window.location.href="/emps"
            console.log(result);//打印服务端返回的数据(调试用)
            if (result.resultCode == 200) {
                alert("SUCCESS");
            };
        },
        error : function(s,s2,s3) {
            //数据成功传到后台 也有返回值 但就是报错 parsererror :参考
            // https://blog.csdn.net/AinGates/article/details/75250223 /
            /*
                        写了一个ajax方法,后台一切正常,通过浏览器的F12工具查看XMLHttpRequest.status返回200,XMLHttpRequest.readyState返回4,也都没有问题。但是回调函数跳到error里,报parsererror的错误。经过排查,发现是因为后台返回时用了@ResponseBody注解(SpringMVC返回json格式的注解),但前台ajax提交没有定义dataType属性(定义服务器返回的数据类型)
                        还有一种情况是ajax方法中定义了 dataType:"json"属性,就一定要返回标准格式的json字符串,要不jQuery1.4+以上版本会报错的,因为不是用eval生成对象了,用的JSON.parse,如果字符串不标准就会报错。比如只返回一个简单的字符串“success”,“fail”, true,false,并不是标准的json字符串就会报错。
                               首先,jQuery 1.4版本之后对服务端返回的JSON 数据要求比较严格,必须严格按照JSON的标准来了。
                    */
            console.log(s)
            console.log(s2)
            console.log(s3)
            alert("异常!");
        }
    })
    }
</script>
</body>
</html>


update 修改代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div>11111111111</div>
<form method="post" onsubmit="return false" action="##" id="update">
    id:<input type="text" name="id" th:value="${userEntity!=null}?${userEntity.id}"><br>
    name:<input type="text" name="name" th:value="${userEntity!=null}?${userEntity.name}"><br>
    login:<input type="text" name="login" th:value="${userEntity!=null}?${userEntity.login}"><br>
    password:<input type="text" name="password" th:value="${userEntity!=null}?${userEntity.password}"><br>
    <input type="button" value="修改" onclick="loginsa()">
</form>
<!--      html页面可用-->
<!--        <script type="text/javascript" src="../static/js/jquery.min.js"></script>-->
<!--         <script type="text/javascript" src="../static/js/jquery.easyui.min.js"></script>-->
<!--  springboot-->
<script src="/js/jquery.min.js"></script>
<script type="text/javascript" src="/js/jquery.easyui.min.js"></script>
<script type="text/javascript">
    function loginsa(){
        $.ajax({
            type:"POST",//方法类型
            dataType: "text",//预期服务器返回的数据类型 如果是对象返回的是json 如果是字符串这里一定要定义text 之前我就是定义json 结果字符串的返回一直到额error中去
            /*
            dataType:
                要求为String类型的参数,预期服务器返回的数据类型。如果不指定,JQuery将自动根据http包mime信息返回responseXML或responseText,并作为回调函数参数传递。可用的类型如下:
                xml:返回XML文档,可用JQuery处理。
                html:返回纯文本HTML信息;包含的script标签会在插入DOM时执行。
                script:返回纯文本JavaScript代码。不会自动缓存结果。除非设置了cache参数。注意在远程请求时(不在同一个域下),所有post请求都将转为get请求。
                json:返回JSON数据。
                jsonp:JSONP格式。使用SONP形式调用函数时,例如myurl?callback=?,JQuery将自动替换后一个“?”为正确的函数名,以执行回调函数。
                text:返回纯文本字符串。
            */
            url:"/updatehtml",
            data:$('#update').serialize(),
            success: function (result) {
                alert("成功")
                window.location.href="/emps"
                console.log(result);//打印服务端返回的数据(调试用)
                if (result.resultCode == 200) {
                    alert("SUCCESS");
                };
            },
            error : function(s,s2,s3) {
                //数据成功传到后台 也有返回值 但就是报错 parsererror :参考
                // https://blog.csdn.net/AinGates/article/details/75250223 /
                /*
                            写了一个ajax方法,后台一切正常,通过浏览器的F12工具查看XMLHttpRequest.status返回200,XMLHttpRequest.readyState返回4,也都没有问题。但是回调函数跳到error里,报parsererror的错误。经过排查,发现是因为后台返回时用了@ResponseBody注解(SpringMVC返回json格式的注解),但前台ajax提交没有定义dataType属性(定义服务器返回的数据类型)
                            还有一种情况是ajax方法中定义了 dataType:"json"属性,就一定要返回标准格式的json字符串,要不jQuery1.4+以上版本会报错的,因为不是用eval生成对象了,用的JSON.parse,如果字符串不标准就会报错。比如只返回一个简单的字符串“success”,“fail”, true,false,并不是标准的json字符串就会报错。
                                   首先,jQuery 1.4版本之后对服务端返回的JSON 数据要求比较严格,必须严格按照JSON的标准来了。
                        */
                console.log(s)
                console.log(s2)
                console.log(s3)
                alert("异常!");
            }
        })
    }
</script>
</body>
</html>


展示一部分效果给大家看看吧


http://localhost:1234/emps


编辑页面

新增页面


数据库展示图:



码云地址:https://gitee.com/yan_wen_chao/spring-boot-simple-crud.git

源码附上


希望大家先手动写 不要什么都不去学不去做;


到这里我就分享结束啦 希望可以帮助到大家;有任何问题可以联系我 看到我会及时回复;

相关实践学习
基于CentOS快速搭建LAMP环境
本教程介绍如何搭建LAMP环境,其中LAMP分别代表Linux、Apache、MySQL和PHP。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助 &nbsp; &nbsp; 相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
相关文章
|
8天前
|
运维 监控 安全
云HIS医疗管理系统源码——技术栈【SpringBoot+Angular+MySQL+MyBatis】
云HIS系统采用主流成熟技术,软件结构简洁、代码规范易阅读,SaaS应用,全浏览器访问前后端分离,多服务协同,服务可拆分,功能易扩展;支持多样化灵活配置,提取大量公共参数,无需修改代码即可满足不同客户需求;服务组织合理,功能高内聚,服务间通信简练。
26 4
|
12天前
|
Java 关系型数据库 MySQL
一套java+ spring boot与vue+ mysql技术开发的UWB高精度工厂人员定位全套系统源码有应用案例
UWB (ULTRA WIDE BAND, UWB) 技术是一种无线载波通讯技术,它不采用正弦载波,而是利用纳秒级的非正弦波窄脉冲传输数据,因此其所占的频谱范围很宽。一套UWB精确定位系统,最高定位精度可达10cm,具有高精度,高动态,高容量,低功耗的应用。
一套java+ spring boot与vue+ mysql技术开发的UWB高精度工厂人员定位全套系统源码有应用案例
|
15天前
|
PHP
web简易开发——通过php与HTML+css+mysql实现用户的登录,注册
web简易开发——通过php与HTML+css+mysql实现用户的登录,注册
|
19天前
|
消息中间件 Java 关系型数据库
JAVA云HIS医院管理系统源码、基于Angular+Nginx+ Java+Spring,SpringBoot+ MySQL + MyCat
JAVA云HIS医院管理系统 常规模版包括门诊管理、住院管理、药房管理、药库管理、院长查询、电子处方、物资管理、媒体管理等,为医院管理提供更有力的保障。 HIS系统以财务信息、病人信息和物资信息为主线,通过对信息的收集、存储、传递、统计、分析、综合查询、报表输出和信息共享,及时为医院领导及各部门管理人员提供全面、准确的各种数据。
|
19天前
|
消息中间件 缓存 运维
java+saas模式医院云HIS系统源码Java+Spring+MySQL + MyCat融合BS版电子病历系统,支持电子病历四级
云HIS系统是一款满足基层医院各类业务需要的健康云产品。该产品能帮助基层医院完成日常各类业务,提供病患预约挂号支持、病患问诊、电子病历、开药发药、会员管理、统计查询、医生工作站和护士工作站等一系列常规功能,还能与公卫、PACS等各类外部系统融合,实现多层机构之间的融合管理。
39 1
|
21天前
|
监控 数据可视化 安全
智慧工地SaaS可视化平台源码,PC端+APP端,支持二开,项目使用,微服务+Java++vue+mysql
环境实时数据、动态监测报警,实时监控施工环境状态,有针对性地预防施工过程中的环境污染问题,打造文明生态施工,创造绿色的生态环境。
15 0
智慧工地SaaS可视化平台源码,PC端+APP端,支持二开,项目使用,微服务+Java++vue+mysql
|
21天前
|
监控 安全 关系型数据库
基于vue2 + element +mysql医院不良事件上报系统源码
不良事件管理系统从时间上报、PDCA分析、事件整改、评估效果实行闭环管理和分析,满足医院追根溯源,全流程闭环管理,提高不良事件上报率,减少同类不良事件发生,提高医疗安全。通过报告不良事件,及时发现潜在的不安全因素
19 1
|
MySQL 关系型数据库 数据库
|
20天前
|
前端开发 JavaScript 开发工具
【HTML/CSS】入门导学篇
【HTML/CSS】入门导学篇
23 0
|
22天前
|
JavaScript 前端开发
【快捷键配置】常用HTML类名、CSS样式名称、JS方法变量名、vue代码片段
【快捷键配置】常用HTML类名、CSS样式名称、JS方法变量名、vue代码片段