将方法和参数传入,service层通过反射调用mapper接口中的方法
测试结果:
Controller
@RequestMapping("/invoke/{methodName}/{param}") @ResponseBody public String invoke(@PathVariable("methodName") String methodName, @PathVariable("param") String param) { Employee employee = employeeService.invoke(methodName, param); System.out.println("查询结果:" + employee); return employee.toString(); }
service
@Override public Employee invoke(String methodName, String param) { Employee employee = new Employee(); // 利用反射获取mapper接口中指定方法,执行 // 获取字节码文件对象 Class<? extends EmpMapper> clazz = empMapper.getClass(); try { // 获取方法 Method method = clazz.getDeclaredMethod(methodName, String.class); // 执行 employee = (Employee) method.invoke(empMapper, param); // 对某些方法做额外处理 if ("findEmpByEname".equals(methodName)) { System.out.println("调用了通过名字查询数据方法"); } } catch (Exception e) { e.printStackTrace(); } return employee; }
mapper接口
Employee findEmpById(String empno);
Employee findEmpByEname(String ename);
mapper.xml
<select id="findEmpById" parameterType="string" resultType="com.alphajuns.pojo.Employee"> select * from emp where empno = #{empno} </select> <select id="findEmpByEname" parameterType="string" resultType="com.alphajuns.pojo.Employee"> select * from emp where ename = #{ename} </select>