SSM練習--CURD以後端代碼

經過Mybatis的逆向工程生成com.ssm.bean,com.ssm.dao,mapper下的文件java

 

 

 1.   逆向工程生成的數據庫操做爲單表操做,若要多表操做須要在xml文件下添加相關 的代碼以下添加查詢員工信息時能夠查詢部門信息sql

<!-- ===========新增多表查詢============= -->
     
     <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 方法json

public Department getDepartment() {
        return department;
    }

    public void setDepartment(Department department) {
        this.department = department;
    }

3.EmployeeMapper添加新定義的兩個多表聯查方法app

 List<Employee> selectByExampleWithDept(EmployeeExample example);

 Employee selectByPrimaryKeyWithDept(Integer empId);

4.業務模塊的邏輯應用設計EmployeeService.java,用@Service標註this

  4.1查詢全部員工信息spa

 

@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查詢員工code

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();
        }
}
相關文章
相關標籤/搜索