SSM练习--CURD之后端代码
通过Mybatis的逆向工程生成com.ssm.bean,com.ssm.dao,mapper下的文件
1. 逆向工程生成的数据库操作为单表操作,若要多表操作需要在xml文件下添加相关 的代码如下添加查询员工信息时可以查询部门信息
<!-- ===========新增多表查询============= --> <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> <resultMap id="WithDeptResultMap" type="com.ssm.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" /> <!-- 指定联合查询的部门字段的封装 --> <association property="department" javaType="com.ssm.bean.Department"> <id column="dept_id" jdbcType="INTEGER" property="deptId" /> <result column="dept_name" jdbcType="VARCHAR" property="deptName" /> </association> </resultMap> <!-- 带条件的多表查询 --> <select id="selectByExampleWithDept" resultMap="WithDeptResultMap"> select <if test="distinct"> distinct </if> <include refid="WithDept_Column_List" /> FROM emp e LEFT JOIN 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 emp e LEFT JOIN dept d ON e.d_id=d.dept_id where emp_id = #{empId,jdbcType=INTEGER} </select>
2.在Employee.java中添加部门字段
//查询员工的同时部门信息也查询出来 private Department department;
以及getter和setter 方法
public Department getDepartment() { return department; } public void setDepartment(Department department) { this.department = department; }
3.EmployeeMapper添加新定义的两个多表联查方法
List<Employee> selectByExampleWithDept(EmployeeExample example);
Employee selectByPrimaryKeyWithDept(Integer empId);
4.业务模块的逻辑应用设计EmployeeService.java,用@Service标注
4.1查询所有员工信息
@Service public class EmployeeService { @Autowired//自动注入 EmployeeMapper employeeMapper; //查询所有员工信息 public List<Employee> getAll(){ return employeeMapper.selectByExampleWithDept(null); }
4.2 保存员工信息
public void saveEmp(Employee employee) { employeeMapper.insertSelective(employee); }
4.3 检查用户名是否可用
public boolean checkUser(String empName) { EmployeeExample example = new EmployeeExample(); Criteria criteria = example.createCriteria(); criteria.andEmpNameEqualTo(empName); long count = employeeMapper.countByExample(example); return count == 0; }
4.4 按照员工id查询员工
public Employee getEmp(Integer id) { Employee employee = employeeMapper.selectByPrimaryKey(id); return employee; }
4.5 更新员工数据
public void updateEmp(Employee employee) { //按照主键有选择更新,因为设定名字是不能更改的 employeeMapper.updateByPrimaryKeySelective(employee); }
4.6 单个删除与批量删除
public void deleteEmp(Integer id) { employeeMapper.deleteByPrimaryKey(id); } //批量删除 public void deleteBatch(List<Integer> ids) { EmployeeExample example = new EmployeeExample(); Criteria criteria = example.createCriteria(); //delete from xxx where emp_id in(1,2,3) criteria.andEmpIdIn(ids); employeeMapper.deleteByExample(example); } }
5.业务模块流程的控制EmployeeController.java 用@Controller标注
5.1信息查询及分页信息
@Controller public class EmployeeController { @Autowired EmployeeService employeeService; //@ResponseBody使用,需要导入jackson包,返回json格式 @RequestMapping("/emps") @ResponseBody //返回Msg数据 public Msg getEmpsWithJson(@RequestParam(value = "pn", defaultValue = "1") Integer pn){ // 引入PageHelper分页插件 // 在查询之前只需要调用 pn=第几页,5=每页多少条 PageMethod.startPage(pn, 3); // startPage后紧跟的查询就是一个分页查询 List<Employee> emps = employeeService.getAll(); // pageinfo包装查询后的结果,只需要pageinfo交给页面,封装了详细的信息 // 5=传入分页连续显示的页数 PageInfo page = new PageInfo(emps, 5); return Msg.success().add("pageInfo",page); }
5.2 员工保存
//员工保存 @RequestMapping(value="/emp",method=RequestMethod.POST) @ResponseBody public Msg saveEmp(@Valid Employee employee,BindingResult result){ if(result.hasErrors()){ //将错误信息封装到map中 Map<String,Object> map = new HashMap(); //从result中提取所有字段的校验信息 List<FieldError> errors=result.getFieldErrors(); //遍历错误信息 for(FieldError fieldError : errors){ System.out.println("错误的字段名:"+fieldError.getField()); System.out.println("错误信息:"+fieldError.getDefaultMessage()); map.put(fieldError.getField(),fieldError.getDefaultMessage()); } return Msg.fail().add("errorFields", map); }else{ employeeService.saveEmp(employee); return Msg.success(); } }
5.3 检查数据是否重复
//检查数据信息重复 @RequestMapping("/checkuser") @ResponseBody public Msg checkuser(@RequestParam("empName")String empName){ //先判断用户名是否是合法的表达式 String regx = "(^[a-zA-Z0-9_-]{6,16}$)|(^[\u2E80-\u9FFF]{2,5}$)"; if(!empName.matches(regx)){ return Msg.fail().add("va_msg", "用户名不合法"); } //数据库用户名重复校验 boolean b = employeeService.checkUser(empName); if(b){ return Msg.success(); }else{ return Msg.fail().add("va_msg", "用户名不可用"); } }
5.4 根据id查询员工
//根据id查询员工 把查询到的数据放到Msg对象中 @RequestMapping(value="/emp/{id}",method=RequestMethod.GET) @ResponseBody //@PathVariable指定id是从路径中/emp/{id}拿到的 public Msg getEmp(@PathVariable("id") Integer id){ Employee employee = employeeService.getEmp(id); return Msg.success().add("emp", employee); }
5.5 保存修改的员工信息
//保存修改的员工信息 @RequestMapping(value="/emp/{empId}",method=RequestMethod.PUT) @ResponseBody public Msg savaEmp(Employee employee,HttpServletRequest request){ System.out.println("请求体中的值:"+request.getParameter("gender")); System.out.println("将要更新的数据:"+employee); employeeService.updateEmp(employee); return Msg.success(); }
5.6 员工单个和批量删除
//员工单个和批量删除 @RequestMapping(value="/emp/ids}",method=RequestMethod.DELETE) @ResponseBody public Msg deleteEmpById(@PathVariable("ids") String ids){ if(ids.contains("-")){ List<Integer> del_ids = new ArrayList(); String[] str_ids = ids.split("-"); for(String string : str_ids){ del_ids.add(Integer.parseInt(string)); } employeeService.deleteBatch(del_ids); }else{ Integer id = Integer.parseInt(ids); employeeService.deleteEmp(id); } return Msg.success(); } }
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步