重点类容:
    index.jsp:

    Controller:
    EmployeeController.java

    1. package com.wj.crud.controller;
    2. import com.github.pagehelper.PageHelper;
    3. import com.github.pagehelper.PageInfo;
    4. import com.wj.crud.bean.Employee;
    5. import com.wj.crud.bean.Msg;
    6. import com.wj.crud.service.EmployeeService;
    7. import org.springframework.beans.factory.annotation.Autowired;
    8. import org.springframework.stereotype.Controller;
    9. import org.springframework.validation.BindingResult;
    10. import org.springframework.validation.FieldError;
    11. import org.springframework.web.bind.annotation.*;
    12. import javax.servlet.http.HttpServletRequest;
    13. import javax.validation.Valid;
    14. import java.util.ArrayList;
    15. import java.util.HashMap;
    16. import java.util.List;
    17. import java.util.Map;
    18. @Controller
    19. public class EmployeeController {
    20. @Autowired
    21. EmployeeService employeeService;
    22. /**
    23. * 单个批量二合一
    24. * 批量删除:1-2-3
    25. * 单个删除:1
    26. *
    27. * @param id
    28. * @return
    29. */
    30. @ResponseBody
    31. @RequestMapping(value="/emp/{ids}",method=RequestMethod.DELETE)
    32. public Msg deleteEmp(@PathVariable("ids")String ids){
    33. //批量删除
    34. if(ids.contains("-")){
    35. List<Integer> del_ids = new ArrayList<Integer>();
    36. String[] str_ids = ids.split("-");
    37. //组装id的集合
    38. for (String string : str_ids) {
    39. del_ids.add(Integer.parseInt(string));
    40. }
    41. employeeService.deleteBatch(del_ids);
    42. }else{
    43. Integer id = Integer.parseInt(ids);
    44. employeeService.deleteEmp(id);
    45. }
    46. return Msg.success();
    47. }
    48. @ResponseBody
    49. @RequestMapping(value="/emp/{empId}",method=RequestMethod.PUT)
    50. public Msg updataEmp(Employee employee,HttpServletRequest request){
    51. System.out.println("请求体中的值:"+request.getParameter("gender"));
    52. System.out.println("将要更新的员工数据:"+employee);
    53. employeeService.updateEmp(employee);
    54. return Msg.success() ;
    55. }
    56. //根据id查询员工数据
    57. @RequestMapping(value = "/emp/{id}",method = RequestMethod.GET) //处理请求 get方式就是查询
    58. @ResponseBody //返回的数据用 @ResponseBody
    59. public Msg getEmp(@PathVariable("id") Integer id){
    60. //id来源于请求路径变量 @PathVariable("id") value = "/emp/{id}
    61. Employee employee = employeeService.getEmp(id);
    62. return Msg.success().add("emp",employee);
    63. }
    64. @ResponseBody
    65. @RequestMapping("/checkuser")
    66. public Msg checkuser(String empName){
    67. //@Request明确的指明要取出empName值
    68. //先判断用户名是否是合法的表达式;
    69. String regx = "(^[a-zA-Z0-9_-]{6,16}$)|(^[\u2E80-\u9FFF]{2,5})";
    70. if(!empName.matches(regx)){
    71. return Msg.fail().add("va_msg", "用户名必须是6-16位数字和字母的组合或者2-5位中文");
    72. }
    73. boolean b = employeeService.checkUser(empName);
    74. if (b){
    75. return Msg.success();
    76. }else {
    77. return Msg.fail().add("va_msg","用户名不可用");
    78. }
    79. }
    80. @RequestMapping(value = "/emp",method = RequestMethod.POST)
    81. @ResponseBody
    82. public Msg saveEmp(@Valid Employee employee, BindingResult result){
    83. //BindingResult 为校验结果
    84. if(result.hasErrors()){
    85. Map<String,Object> map = new HashMap<String, Object>();
    86. //校验失败,应该返回失败错误信息
    87. List<FieldError> errors = result.getFieldErrors();
    88. for (FieldError fieldError : errors){
    89. System.out.println(fieldError.getField());
    90. System.out.println("错误信息:"+fieldError.getDefaultMessage());
    91. map.put(fieldError.getField(),fieldError.getDefaultMessage());
    92. }
    93. return Msg.fail().add("errorFields",map);
    94. }else {
    95. employeeService.saveEmp(employee);
    96. return Msg.success();
    97. }
    98. }
    99. @RequestMapping("/emps")
    100. @ResponseBody //将返回的json对象转化为字符串 需要在pom.xml导入json包
    101. public Msg getEmpsWithJson(@RequestParam(value = "pn", defaultValue = "1") Integer pn){
    102. PageHelper.startPage(pn, 5);
    103. // startPage后面紧跟的这个查询就是一个分页查询
    104. List<Employee> emps = employeeService.getAll();
    105. // 使用pageInfo包装查询后的结果,只需要将pageInfo交给页面就行了。
    106. // 封装了详细的分页信息,包括有我们查询出来的数据,传入连续显示的页数
    107. PageInfo page = new PageInfo(emps, 5);
    108. return Msg.success().add("pageInfo",page);
    109. }
    110. //@RequestMapping("/emps")
    111. // public String getEmps(
    112. // @RequestParam(value = "pn", defaultValue = "1") Integer pn,
    113. // Model model) {
    114. // // 这不是一个分页查询;
    115. // // 引入PageHelper分页插件
    116. // // 在查询之前只需要调用,传入页码,以及每页的大小
    117. // PageHelper.startPage(pn, 5);
    118. // // startPage后面紧跟的这个查询就是一个分页查询
    119. // List<Employee> emps = employeeService.getAll();
    120. // // 使用pageInfo包装查询后的结果,只需要将pageInfo交给页面就行了。
    121. // // 封装了详细的分页信息,包括有我们查询出来的数据,传入连续显示的页数
    122. // PageInfo page = new PageInfo(emps, 5);
    123. // model.addAttribute("pageInfo", page);
    124. //
    125. // return "list";
    126. // }
    127. }

    service:
    EmployeeService.java

    package com.wj.crud.service;
    
    import com.wj.crud.bean.Employee;
    import com.wj.crud.bean.EmployeeExample;
    import com.wj.crud.dao.EmployeeMapper;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    import com.wj.crud.bean.EmployeeExample.Criteria;
    
    import java.util.List;
    
    @Service
    public class EmployeeService {
        @Autowired
        EmployeeMapper employeeMapper;
    
        /**
         * 查询所有员工
         * @return
         */
        public List<Employee> getAll() {
            // TODO Auto-generated method stub
            return employeeMapper.selectByExampleWithDept(null);
        }
    
            //员工保存
        public void saveEmp(Employee employee) {
            employeeMapper.insertSelective(employee);
        }
    
        /**
         * 检验用户名是否可用
         *
         * @param empName
         * @return  true:代表当前姓名可用   fasle:不可用
         */
        public boolean checkUser(String empName) {
            // TODO Auto-generated method stub
            EmployeeExample example = new EmployeeExample();
            Criteria criteria = example.createCriteria();
            criteria.andEmpNameEqualTo(empName);
            long count = employeeMapper.countByExample(example);
            return count == 0;
        }
    
        //按照员工id查询员工
        public Employee getEmp(Integer id) {
            Employee employee = employeeMapper.selectByPrimaryKeyWithDept(id);
            return employee;
        }
    
        //更新员工方法
        public void updateEmp(Employee employee) {
            employeeMapper.updateByPrimaryKeySelective(employee);
        }
    
        public void deleteEmp(Integer id) {
            //按照主键删除
            employeeMapper.deleteByPrimaryKey(id);
        }
    
    
        public void deleteBatch(List<Integer> ids) {
            // TODO Auto-generated method stub
            EmployeeExample example = new EmployeeExample();
            Criteria criteria = example.createCriteria();
            //delete from xxx where emp_id in(1,2,3)
            criteria.andEmpIdIn(ids);
            employeeMapper.deleteByExample(example);
        }
    
    
    
    
    }
    

    dao:
    EmployeeMapper.java

    package com.wj.crud.dao;
    
    import com.wj.crud.bean.Employee;
    import com.wj.crud.bean.EmployeeExample;
    import java.util.List;
    import org.apache.ibatis.annotations.Param;
    import org.springframework.stereotype.Repository;
    
    @Repository
    public interface EmployeeMapper {
        long countByExample(EmployeeExample example);
    
        int deleteByExample(EmployeeExample example);
    
        int deleteByPrimaryKey(Integer empId);
    
        int insert(Employee record);
    
        int insertSelective(Employee record);
    
        List<Employee> selectByExample(EmployeeExample example);
    
        Employee selectByPrimaryKey(Integer empId);
    
        List<Employee> selectByExampleWithDept(EmployeeExample example);
    
        Employee selectByPrimaryKeyWithDept(Integer empId);
    
        int updateByExampleSelective(@Param("record") Employee record, @Param("example") EmployeeExample example);
    
        int updateByExample(@Param("record") Employee record, @Param("example") EmployeeExample example);
    
        int updateByPrimaryKeySelective(Employee record);
    
        int updateByPrimaryKey(Employee record);
    }
    

    mapper:
    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.wj.crud.dao.EmployeeMapper">
      <resultMap id="BaseResultMap" type="com.wj.crud.bean.Employee">
        <id column="emp_id" jdbcType="INTEGER" property="empId" />
        <result column="emp_name" jdbcType="VARCHAR" property="empName" />
        <result column="gender" jdbcType="CHAR" property="gender" />
        <result column="email" jdbcType="VARCHAR" property="email" />
        <result column="d_id" jdbcType="INTEGER" property="dId" />
      </resultMap>
      <sql id="Example_Where_Clause">
        <where>
          <foreach collection="oredCriteria" item="criteria" separator="or">
            <if test="criteria.valid">
              <trim prefix="(" prefixOverrides="and" suffix=")">
                <foreach collection="criteria.criteria" item="criterion">
                  <choose>
                    <when test="criterion.noValue">
                      and ${criterion.condition}
                    </when>
                    <when test="criterion.singleValue">
                      and ${criterion.condition} #{criterion.value}
                    </when>
                    <when test="criterion.betweenValue">
                      and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
                    </when>
                    <when test="criterion.listValue">
                      and ${criterion.condition}
                      <foreach close=")" collection="criterion.value" item="listItem" open="(" separator=",">
                        #{listItem}
                      </foreach>
                    </when>
                  </choose>
                </foreach>
              </trim>
            </if>
          </foreach>
        </where>
      </sql>
      <sql id="Update_By_Example_Where_Clause">
        <where>
          <foreach collection="example.oredCriteria" item="criteria" separator="or">
            <if test="criteria.valid">
              <trim prefix="(" prefixOverrides="and" suffix=")">
                <foreach collection="criteria.criteria" item="criterion">
                  <choose>
                    <when test="criterion.noValue">
                      and ${criterion.condition}
                    </when>
                    <when test="criterion.singleValue">
                      and ${criterion.condition} #{criterion.value}
                    </when>
                    <when test="criterion.betweenValue">
                      and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
                    </when>
                    <when test="criterion.listValue">
                      and ${criterion.condition}
                      <foreach close=")" collection="criterion.value" item="listItem" open="(" separator=",">
                        #{listItem}
                      </foreach>
                    </when>
                  </choose>
                </foreach>
              </trim>
            </if>
          </foreach>
        </where>
      </sql>
      <sql id="Base_Column_List">
        emp_id, emp_name, gender, email, d_id
      </sql>
    
    
    
    
    
    
      <resultMap type="com.wj.crud.bean.Employee" id="WithDeptResultMap">
        <id column="emp_id" jdbcType="INTEGER" property="empId" />
        <result column="emp_name" jdbcType="VARCHAR" property="empName" />
        <result column="gender" jdbcType="CHAR" property="gender" />
        <result column="email" jdbcType="VARCHAR" property="email" />
        <result column="d_id" jdbcType="INTEGER" property="dId" />
        <!-- 指定联合查询出的部门字段的封装 -->
        <association property="department" javaType="com.wj.crud.bean.Department">
          <id column="dept_id" property="deptId"/>
          <result column="dept_name" property="deptName"/>
        </association>
      </resultMap>
    
    
      <sql id="WithDept_Column_List">
          e.emp_id, e.emp_name, e.gender, e.email, e.d_id,d.dept_id,d.dept_name
      </sql>
    
      <!-- 查询员工同时带部门信息 -->
      <select id="selectByExampleWithDept" resultMap="WithDeptResultMap">
        select
        <if test="distinct">
          distinct
        </if>
        <include refid="WithDept_Column_List" />
        FROM tbl_emp e
        left join tbl_dept d on e.`d_id`=d.`dept_id`
        <if test="_parameter != null">
          <include refid="Example_Where_Clause" />
        </if>
        <if test="orderByClause != null">
          order by ${orderByClause}
        </if>
      </select>
      <select id="selectByPrimaryKeyWithDept" resultMap="WithDeptResultMap">
        select
        <include refid="WithDept_Column_List" />
        FROM tbl_emp e
        left join tbl_dept d on e.`d_id`=d.`dept_id`
        where emp_id = #{empId,jdbcType=INTEGER}
      </select>
    
      <select id="selectByExample" parameterType="com.wj.crud.bean.EmployeeExample" resultMap="BaseResultMap">
        select
        <if test="distinct">
          distinct
        </if>
        <include refid="Base_Column_List" />
        from tbl_emp
        <if test="_parameter != null">
          <include refid="Example_Where_Clause" />
        </if>
        <if test="orderByClause != null">
          order by ${orderByClause}
        </if>
      </select>
      <select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
        select 
        <include refid="Base_Column_List" />
        from tbl_emp
        where emp_id = #{empId,jdbcType=INTEGER}
      </select>
      <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
        delete from tbl_emp
        where emp_id = #{empId,jdbcType=INTEGER}
      </delete>
      <delete id="deleteByExample" parameterType="com.wj.crud.bean.EmployeeExample">
        delete from tbl_emp
        <if test="_parameter != null">
          <include refid="Example_Where_Clause" />
        </if>
      </delete>
      <insert id="insert" parameterType="com.wj.crud.bean.Employee">
        insert into tbl_emp (emp_id, emp_name, gender, 
          email, d_id)
        values (#{empId,jdbcType=INTEGER}, #{empName,jdbcType=VARCHAR}, #{gender,jdbcType=CHAR}, 
          #{email,jdbcType=VARCHAR}, #{dId,jdbcType=INTEGER})
      </insert>
      <insert id="insertSelective" parameterType="com.wj.crud.bean.Employee">
        insert into tbl_emp
        <trim prefix="(" suffix=")" suffixOverrides=",">
          <if test="empId != null">
            emp_id,
          </if>
          <if test="empName != null">
            emp_name,
          </if>
          <if test="gender != null">
            gender,
          </if>
          <if test="email != null">
            email,
          </if>
          <if test="dId != null">
            d_id,
          </if>
        </trim>
        <trim prefix="values (" suffix=")" suffixOverrides=",">
          <if test="empId != null">
            #{empId,jdbcType=INTEGER},
          </if>
          <if test="empName != null">
            #{empName,jdbcType=VARCHAR},
          </if>
          <if test="gender != null">
            #{gender,jdbcType=CHAR},
          </if>
          <if test="email != null">
            #{email,jdbcType=VARCHAR},
          </if>
          <if test="dId != null">
            #{dId,jdbcType=INTEGER},
          </if>
        </trim>
      </insert>
      <select id="countByExample" parameterType="com.wj.crud.bean.EmployeeExample" resultType="java.lang.Long">
        select count(*) from tbl_emp
        <if test="_parameter != null">
          <include refid="Example_Where_Clause" />
        </if>
      </select>
      <update id="updateByExampleSelective" parameterType="map">
        update tbl_emp
        <set>
          <if test="record.empId != null">
            emp_id = #{record.empId,jdbcType=INTEGER},
          </if>
          <if test="record.empName != null">
            emp_name = #{record.empName,jdbcType=VARCHAR},
          </if>
          <if test="record.gender != null">
            gender = #{record.gender,jdbcType=CHAR},
          </if>
          <if test="record.email != null">
            email = #{record.email,jdbcType=VARCHAR},
          </if>
          <if test="record.dId != null">
            d_id = #{record.dId,jdbcType=INTEGER},
          </if>
        </set>
        <if test="_parameter != null">
          <include refid="Update_By_Example_Where_Clause" />
        </if>
      </update>
      <update id="updateByExample" parameterType="map">
        update tbl_emp
        set emp_id = #{record.empId,jdbcType=INTEGER},
          emp_name = #{record.empName,jdbcType=VARCHAR},
          gender = #{record.gender,jdbcType=CHAR},
          email = #{record.email,jdbcType=VARCHAR},
          d_id = #{record.dId,jdbcType=INTEGER}
        <if test="_parameter != null">
          <include refid="Update_By_Example_Where_Clause" />
        </if>
      </update>
      <update id="updateByPrimaryKeySelective" parameterType="com.wj.crud.bean.Employee">
        update tbl_emp
        <set>
          <if test="empName != null">
            emp_name = #{empName,jdbcType=VARCHAR},
          </if>
          <if test="gender != null">
            gender = #{gender,jdbcType=CHAR},
          </if>
          <if test="email != null">
            email = #{email,jdbcType=VARCHAR},
          </if>
          <if test="dId != null">
            d_id = #{dId,jdbcType=INTEGER},
          </if>
        </set>
        where emp_id = #{empId,jdbcType=INTEGER}
      </update>
      <update id="updateByPrimaryKey" parameterType="com.wj.crud.bean.Employee">
        update tbl_emp
        set emp_name = #{empName,jdbcType=VARCHAR},
          gender = #{gender,jdbcType=CHAR},
          email = #{email,jdbcType=VARCHAR},
          d_id = #{dId,jdbcType=INTEGER}
        where emp_id = #{empId,jdbcType=INTEGER}
      </update>
    </mapper>