zoukankan      html  css  js  c++  java
  • spring项目篇3----编写用户展示模块

    第一步创建两张数据库表

    员工表:

    部门表:

    第二步:

    使用之前配置的mybatis-generator自动从数据库中生成pojo类与mapper映射文件

    首先在配置文件中添加我们的表信息

    <!--指定生成那个表-->
            <table tableName="employee" />
            <table tableName="department" />

    之后点击运行

    在java.com.yang.mapper包中的xml文件需要移动到resources.com.yang.mapper中,这样spring才能找到

    接下来我们直接看一个这个插件帮助我们生成的文件

    EmployeeMapper

    package com.yang.mapper;
    
    import com.yang.domain.Employee;
    import com.yang.domain.QueryVo;
    
    import java.util.List;
    
    public interface EmployeeMapper {
        int deleteByPrimaryKey(Integer id);
    
        int insert(Employee record);
    
        Employee selectByPrimaryKey(Integer id);
    
        List<Employee> selectAll(QueryVo queryVo);
    
        int updateByPrimaryKey(Employee record);
    }

    EmployeeMapper.xml里面的选择所有以及插入跟更新修改了一下,并添加了一个修改离职状态的数据库操作,但是大体都是差不多的

    <?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.yang.mapper.EmployeeMapper">
      <resultMap id="BaseResultMap" type="com.yang.domain.Employee">
        <id column="id" jdbcType="INTEGER" property="id" />
        <result column="username" jdbcType="VARCHAR" property="username" />
        <result column="password" jdbcType="VARCHAR" property="password" />
        <result column="hiredate" jdbcType="TIMESTAMP" property="hiredate" />
        <result column="phone" jdbcType="VARCHAR" property="phone" />
        <result column="email" jdbcType="VARCHAR" property="email" />
        <result column="state" jdbcType="BIT" property="state" />
        <result column="admin" jdbcType="BIT" property="admin" />
        <association property="department" javaType="com.yang.domain.Department" columnPrefix="d_">
          <result property="id" column="id" />
          <result property="name" column="name" />
        </association>
      </resultMap>
      <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
        delete from employee
        where id = #{id,jdbcType=INTEGER}
      </delete>
      <insert id="insert" parameterType="com.yang.domain.Employee">
        insert into employee (id, username, password, 
          hiredate, phone, email, 
          state, admin, dep_id)
        values (#{id,jdbcType=INTEGER}, #{username,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR}, 
          #{hiredate}, #{phone,jdbcType=VARCHAR}, #{email,jdbcType=VARCHAR},
          #{state}, #{admin,jdbcType=BIT}, #{department.id,jdbcType=INTEGER})
      </insert>
      <update id="updateByPrimaryKey" parameterType="com.yang.domain.Employee">
        update employee
        set username = #{username,jdbcType=VARCHAR},
          hiredate = #{hiredate,jdbcType=TIMESTAMP},
          phone = #{phone,jdbcType=VARCHAR},
          email = #{email,jdbcType=VARCHAR},
          admin = #{admin,jdbcType=BIT},
          dep_id = #{department.id,jdbcType=INTEGER}
        where id = #{id,jdbcType=INTEGER}
      </update>
      <update id="changeState">
        update employee set state = false where id=#{id}
      </update>
      <select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
        select id, username, password, hiredate, phone, email, state, admin, dep_id
        from employee
        where id = #{id,jdbcType=INTEGER}
      </select>
      <select id="selectAll" resultMap="BaseResultMap">
        select e.id, e.username, e.password, e.hiredate, e.phone, e.email, e.state, e.admin, d.id as d_id, d.`name` as d_name
        from employee as e
        left join  department as d
        on e.dep_id = d.id
        <where>
          <if test="keyword != null and keyword != ''">
            and e.username like concat('%',#{keyword},'%')
            or e.phone like concat('%', #{keyword}, '%')
            or e.email like concat('%', #{keyword}, '%')
          </if>
        </where>
      </select>
    </mapper>

    从上可以得出,这个插件可以帮助我们生成生成增删改查四种操作的迎神文件·映射文件以及domian中的pojo类,只需要再修改一下细节就可以了

    生成文件之后,我们看一下关于员工的增删改查

    首先看一下前端页面,我们使用的是easyUi,我把js文件封装到一个文件中

    // common.js
    <link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/static/plugins/easyui/uimaker/easyui.css">
    <link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/static/plugins/easyui/uimaker/icon.css">
    <script type="text/javascript" src="${pageContext.request.contextPath}/static/plugins/easyui/jquery.min.js"></script>
    <script type="text/javascript" src="${pageContext.request.contextPath}/static/plugins/easyui/jquery.easyui.min.js"></script>
    <script type="text/javascript" src="${pageContext.request.contextPath}/static/plugins/easyui/easyui-lang-zh_CN.js"></script>
    <script type="text/javascript" src="${pageContext.request.contextPath}/static/js/base.js"></script>
    // index.jsp
    <%--
      Created by IntelliJ IDEA.
      User: yangshixiong
      Date: 2020/2/8
      Time: 上午12:19
      To change this template use File | Settings | File Templates.
    --%>
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
        <title>员工</title>
        <%--导入公共包以及employee的js文件--%>
        <%@include file="/static/common/common.jsp" %>
        <script type="text/javascript" src="${pageContext.request.contextPath}/static/js/employee.js"></script>
    </head>
    <body>
    <%--工具栏--%>
    <div id="tb">
        <a href="#" class="easyui-linkbutton" data-options="iconCls:'icon-add',plain:true" id="add">添加</a>
        <a href="#" class="easyui-linkbutton" data-options="iconCls:'icon-edit',plain:true" id="edit">编辑</a>
        <a href="#" class="easyui-linkbutton" data-options="iconCls:'icon-remove',plain:true" id="delete">离职</a>
        <a href="#" class="easyui-linkbutton" data-options="iconCls:'icon-reload',plain:true" id="reload">刷新</a>
        <input type="text" name="keyword" style=" 200px; height: 30px;padding-left: 5px;">
        <a class="easyui-linkbutton" iconCls="icon-search" id="searchbtn">查询</a>
    </div>
    <%--数据表格承接--%>
    <table id="dg"></table>
    <%--对话框--%>
    <div id="dialog">
        <form id="employeeForm">
            <%--添加一个隐藏域  编辑--%>
            <input type="hidden" name="id">
            <table align="center" style="border-spacing: 0px 10px">
                <tr>
                    <td>用户名:</td>
                    <td><input type="text" name="username" class="easyui-validatebox" data-options="required:true"></td>
                </tr>
                <tr id="password">
                    <td>密码:</td>
                    <td><input type="text" name="password" class="easyui-validatebox"></td>
                </tr>
                <tr>
                    <td>手机:</td>
                    <td><input type="text" name="phone" class="easyui-validatebox" data-options="required:true"></td>
                </tr>
                <tr>
                    <td>邮箱:</td>
                    <td><input type="text" name="email" class="easyui-validatebox" data-options="required:true,validType:'email'"></td>
                </tr>
                <tr>
                    <td>入职日期:</td>
                    <td><input type="text" name="hiredate" class="easyui-datebox" data-options="required:true"></td>
                </tr>
                <tr>
                    <td>部门:</td>
                    <td><input id="department" name="department.id" placeholder="请选择部门" data-options="required:true"/></td>
                </tr>
                <tr>
                    <td>是否管理员:</td>
                    <td><input id="state" name="admin" placeholder="是否为管理员" data-options="required:true"/></td>
                </tr>
            </table>
        </form>
    
    </div>
    </body>
    </html>

    index.js

    $(function () {
        // 员工数据列表
        $('#dg').datagrid({
            // 数据请求路径
            url: "/employee/list",
            // 加载列表
            columns: [[{field: 'username', title: '姓名',  100, align: 'center'},
                {field: 'hiredate', title: '入职时间',  100, align: 'center'},
                {field: 'phone', title: '电话',  100, align: 'center'},
                {field: 'email', title: '邮箱',  100, align: 'center'},
                // formatter 接受三个参数  value该字段的值, row该行的内容, index 下标
                {
                    field: 'department', title: '部门',  100, align: 'center', formatter: function (value, row, index) {
                        if (value) {
                            return value.name;
                        }
                    }
                },
                {
                    field: 'state', title: '状态',  100, align: 'center', formatter: function (value, row, index) {
                        if (value) {
                            return "在职";
                        } else {
                            return "<span style='color:red'>离职</span>"
                        }
                    }
                },
                {
                    field: 'admin', title: '管理员',  100, align: 'center', formatter: function (value, row, index) {
                        if (row.admin) {
                            return "是";
                        }else {
                            return "否";
                        }
                    }
                },
            ]],
            // 是否铺满屏幕
            fit: true,
            // 数据列是否自适应
            fitColumns: true,
            // 显示行号
            rownumbers: true,
            // 是否显示翻页
            pagination: true,
            // 只允许选中一条数据
            singleSelect: true,
            // 工具栏
            toolbar:"#tb",
            onClickRow:function (rowIndex,rowData) {
                /*判断当前行是否是离职状态*/
                if(!rowData.state){
                    /*离职,把离职按钮禁用*/
                    $("#delete").linkbutton("disable");
                }else {
                    /*离职,把离职按钮启用*/
                    $("#delete").linkbutton("enable");
                }
            }
    
        });
    
        // 对话框
        $('#dialog').dialog({
            350,
            height:370,
            // 默认关闭状态
            closed:true,
            // 设置按钮
            buttons:[{
                text:'保存',
                handler:function () {
                    // 判断当前是保存还是添加
                    let id = $("[name='id']").val();
                    let url;
                    if(id){
                        url = '/employee/update'
                    }else{
                        url = '/employee/add'
                    }
                    // 提交表单
                    $("#employeeForm").form("submit",{
                        url:url,
                        success:function (data) {
                            data = $.parseJSON(data);
                            if(data.success){
                                $.messager.alert("提示", data.msg);
                                $("#dialog").dialog("close");
                                $("#dg").datagrid("reload")
                            }else{
                                $.messager.alert("警告", data.msg);
                            }
                        }
                    })
                }
            },{
                text: '关闭',
                handler:function () {
                    $('#dialog').dialog("close");
                }
            }]
        });
    
        // 监听添加按钮点击
        $("#add").click(function () {
            // 设置dialog的标题
            $("#dialog").dialog("setTitle", "添加员工");
            $("#password").show();
            // 清空对话框的数据
            $("#employeeForm").form("clear");
            // 添加密码验证
            $("[name='password']").validatebox({required:true});
            // 打开对话框
            $("#dialog").dialog("open")
        });
    
        // 监听编辑按钮点击
        $("#edit").click(function () {
            // 获取当前选中的数据
            let rowData = $("#dg").datagrid("getSelected");
            if(!rowData){
                $.messager.alert("提示", "请选择一条数据进行编辑!");
                return
            }
            // 取消密码验证并将密码隐藏
            $("[name='password']").validatebox({required: false});
            $("#password").hide();
            // 弹出对话框
            $("#dialog").dialog("setTitle", "编辑员工");
            $("#dialog").dialog("open");
            // 设置部门回显
            rowData["department.id"] = rowData["department"].id;
            // 回显管理员
            rowData["admin"] = rowData["admin"] + "";
            // 将数据回显
            $("#employeeForm").form("load", rowData)
        });
    
        /*部门选择 下拉列表*/
        $("#department").combobox({
            150,
            panelHeight:'auto',
            editable:false,
            url:'/department/list',
            textField:'name',
            valueField:'id',
            onLoadSuccess:function () { /*数据加载完毕之后回调*/
                $("#department").each(function(i){
                    let span = $(this).siblings("span")[i];
                    let targetInput = $(span).find("input:first");
                    if(targetInput){
                        $(targetInput).attr("placeholder", $(this).attr("placeholder"));
                    }
                });
            }
        });
    
        /*是否为管理员选择*/
        $("#state").combobox({
            150,
            panelHeight:'auto',
            textField:'label',
            valueField:'value',
            editable:false,
            data:[{
                label:'是',
                value:'true'
            },{
                label:'否',
                value:'false'
            }],
            onLoadSuccess:function () { /*数据加载完毕之后回调*/
                $("#state").each(function(i){
                    let span = $(this).siblings("span")[i];
                    let targetInput = $(span).find("input:first");
                    if(targetInput){
                        $(targetInput).attr("placeholder", $(this).attr("placeholder"));
                    }
                });
            }
    
        });
    
        /*设置离职按钮点击*/
        $("#delete").click(function () {
            /*首先获取当前选中行*/
            let rowData = $("#dg").datagrid("getSelected");
            if(!rowData){
                $.messager.alert("提示","选择一行数据进行编辑");
                return;
            }
            /*提醒用户,是否做离职操作*/
            $.messager.confirm("确认","是否做离职操作",function (res) {
                if(res){
                    /*做离职操作*/
                    $.get("/employee/state?id="+rowData.id,function (data) {
                        if (data.success){
                            $.messager.alert("温馨提示",data.msg);
                            /*重新加载数据表格*/
                            $("#dg").datagrid("reload");
                        } else {
                            $.messager.alert("温馨提示",data.msg);
                        }
    
                    });
                }
            });
        })
    
        /*监听搜索按钮点击*/
        $("#searchbtn").click(function () {
            /*获取搜索的内容*/
            let keyword =  $("[name='keyword']").val();
            /*重新加载列表  把参数keyword传过去*/
            $("#dg").datagrid("load",{keyword:keyword});
        });
    
        /*监听刷新点击*/
        $("#reload").click(function () {
            /*清空搜索内容*/
            let keyword =  $("[name='keyword']").val('')
            /*重新加载数据*/
            $("#dg").datagrid("load",{});
        });
    }); 

     根据table的传值,我们封装一个接受参数的pojo类,get,set方法就不贴了

    package com.yang.domain;
    
    /**
     * 这个就是我们接受参数的一个类
     */
    public class QueryVo {
        // 页码
        private Integer page;
        // 每页条数
        private Integer rows;
        // 关键词
        private String keyword;
    }

    以及一个响应pojo类

    /**
     * 响应
     */
    public class AjaxRes {
    
        private boolean success;
        private String msg;
    
        public boolean isSuccess() {
            return success;
        }
    }

    最终实现我们的增删改查的controller

    package com.yang.web;
    
    import com.yang.domain.AjaxRes;
    import com.yang.domain.Employee;
    import com.yang.domain.PageListRes;
    import com.yang.domain.QueryVo;
    import com.yang.service.EmployeeService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.ResponseBody;
    
    @Controller
    public class EmployeeController {
    
        /*注入业务层*/
        @Autowired
        private EmployeeService employeeService;
    
        /*返回employee的jsp文件*/
        @RequestMapping("/employee")
        public String employee(){
            return "employee";
        }
    
        /*返回员工列表*/
        @RequestMapping("/employee/list")
        @ResponseBody  // 返回json数据
        public PageListRes employeeList(QueryVo queryVo){
            return employeeService.getList(queryVo);
        }
    
        /*增加员工*/
        @RequestMapping("/employee/add")
        @ResponseBody
        public AjaxRes employeeAdd(Employee employee){
            return employeeService.insertEmployee(employee);
        }
    
        /*编辑员工*/
        @RequestMapping("/employee/update")
        @ResponseBody
        public AjaxRes employeeUpdate(Employee employee){
            return employeeService.updateEmployee(employee);
        }
    
        /*离职操作*/
        @RequestMapping("/employee/state")
        @ResponseBody
        public AjaxRes employeeUpdate(Integer id){
            return employeeService.changeState(id);
        }
    }

    看一下service的实现类

    package com.yang.service.impl;
    
    import com.github.pagehelper.Page;
    import com.github.pagehelper.PageHelper;
    import com.yang.domain.AjaxRes;
    import com.yang.domain.Employee;
    import com.yang.domain.PageListRes;
    import com.yang.domain.QueryVo;
    import com.yang.mapper.EmployeeMapper;
    import com.yang.service.EmployeeService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    import org.springframework.transaction.annotation.Transactional;
    
    import java.util.List;
    
    @Service
    @Transactional  // 开启事务,保证事务提交
    public class EmployeeServiceImpl implements EmployeeService {
    
        /*注入员工查询数据库*/
        @Autowired
        private EmployeeMapper employeeMapper;
    
        @Override
        public PageListRes getList(QueryVo queryVo) {
            // 使用分页器
            Page<Object> page = PageHelper.startPage(queryVo.getPage(), queryVo.getRows());
            // 调用mapper查询员工
            List<Employee> employees = employeeMapper.selectAll(queryVo);
            // 封装返回结果
            PageListRes pageListRes = new PageListRes();
            pageListRes.setTotal(page.getTotal());
            pageListRes.setRows(employees);
            return pageListRes;
        }
    
        /*增加员工*/
        @Override
        public AjaxRes insertEmployee(Employee employee) {
            employee.setState(true);
            int result = employeeMapper.insert(employee);
            AjaxRes ajaxRes = new AjaxRes();
            if(result == 1){
                ajaxRes.setSuccess(true);
                ajaxRes.setMsg("插入成功!");
            }else{
                ajaxRes.setMsg("插入失败,请重试!");
                ajaxRes.setSuccess(false);
            }
            return ajaxRes;
        }
    
        /*修改员工*/
        @Override
        public AjaxRes updateEmployee(Employee employee) {
            int result = employeeMapper.updateByPrimaryKey(employee);
            AjaxRes ajaxRes = new AjaxRes();
            if(result == 1){
                ajaxRes.setSuccess(true);
                ajaxRes.setMsg("更新成功!");
            }else{
                ajaxRes.setMsg("更新失败,请重试!");
                ajaxRes.setSuccess(false);
            }
            return ajaxRes;
        }
    
        /*修改员工离职状态*/
        @Override
        public AjaxRes changeState(Integer id) {
            int result = employeeMapper.changeState(id);
            AjaxRes ajaxRes = new AjaxRes();
            if(result == 1){
                ajaxRes.setSuccess(true);
                ajaxRes.setMsg("离职操作成功!");
            }else{
                ajaxRes.setMsg("离职操作失败,请重试!");
                ajaxRes.setSuccess(false);
            }
            return ajaxRes;
        }
    }

         

  • 相关阅读:
    序列化 Serialization
    http soap关系
    sql 查询
    返回最后插入到标识列的值(scope_identity.ident_current.@@identity)
    匿名方法
    九、volatile与Java内存模型
    八、Java内存模型JMM
    十、CAS
    CUSTOM ROUTE CONSTRAINTS
    获取本地数据库
  • 原文地址:https://www.cnblogs.com/yangshixiong/p/12285321.html
Copyright © 2011-2022 走看看