本文共 3520 字,大约阅读时间需要 11 分钟。
查询条件不确定,需要根据情况产生SQL语法,这种情况叫动态SQL
StudentMapper.xml
update t_students where stu_id = #{uid} stu_name = #{uname}, stu_sal = #{usal}, delete from t_students where stu_id in #{ids} delete from t_students where stu_id in #{ids} insert into t_students( ) values( ) stu_id, stu_name, stu_sal, #{id}, #{name}, #{sal},
然后在dao层StudentDao封装相应的方法
/** * 动态添加 * @param student */public void dynaAdd(Student student){ SqlSession sqlSession = null; try { sqlSession = MybatisUtil.getSqlSession(); int rows = sqlSession.insert(Student.class.getName() +".dynaAdd",student); System.out.println("更新了" + rows + "行"); sqlSession.commit(); } catch (Exception e) { e.printStackTrace(); sqlSession.rollback(); throw e; }finally{ MybatisUtil.closeSqlSession(); }}/** * 动态更新 * @param id * @param name * @param sal */public void dynaUpdate(Integer id,String name,Double sal){ SqlSession sqlSession = null; try { sqlSession = MybatisUtil.getSqlSession(); Map这样就实现了mybatis的动态SQL,使代码变得更加灵活。map = new LinkedHashMap<>(); map.put("uid", id); map.put("uname", name); map.put("usal", sal); int rows = sqlSession.update(Student.class.getName() +".dynaUpdate",map); System.out.println("更新了" + rows + "行"); sqlSession.commit(); } catch (Exception e) { e.printStackTrace(); sqlSession.rollback(); throw e; }finally{ MybatisUtil.closeSqlSession(); }}/** * 动态查询 * @return */public List dynafindAll(Integer id,String name,Double sal){ SqlSession sqlSession = null; try { sqlSession = MybatisUtil.getSqlSession(); Map map = new LinkedHashMap<>(); map.put("pid", id); map.put("pname", name); map.put("psal", sal); return sqlSession.selectList(Student.class.getName() +".dynafindAll",map); } catch (Exception e) { e.printStackTrace(); throw e; }finally{ MybatisUtil.closeSqlSession(); }}/** * 动态删除(根据ID批量删除学生(数组版本)) * @param id * @param name * @param sal */public void dynaDeleteArray(int...ids){ SqlSession sqlSession = null; try { sqlSession = MybatisUtil.getSqlSession(); int rows = sqlSession.update(Student.class.getName() +".dynaDeleteArray",ids); System.out.println("更新了" + rows + "行"); sqlSession.commit(); } catch (Exception e) { e.printStackTrace(); sqlSession.rollback(); throw e; }finally{ MybatisUtil.closeSqlSession(); }}/** * 动态批量删除(集合) * @param ids */public void dynaDeleteList(List ids){ SqlSession sqlSession = null; try { sqlSession = MybatisUtil.getSqlSession(); int rows = sqlSession.update(Student.class.getName() +".dynaDeleteList",ids); System.out.println("更新了" + rows + "行"); sqlSession.commit(); } catch (Exception e) { e.printStackTrace(); sqlSession.rollback(); throw e; }finally{ MybatisUtil.closeSqlSession(); }}
转载地址:http://wdslf.baihongyu.com/