.1) 入参为HashMap
1.创建sql语句
<!-- 通过hashMap入参来通过家庭地址或者学校地址插叙学生--> <select id="selectStudentByhomeOrSchoolMap" resultType="Student" parameterType="Map"> select stuno,stuName from student where homeaddress=#{homeAddress} or schooladdress=#{schoolAddress} </select>
2.编写接口
/** * * @param map * @return */ List<Student> selectStudentByhomeOrSchoolMap(Map<String,Object> map);
3.测试类
public static void selectAllOrderByhomeOrSchoolMap() throws IOException { Reader reader = Resources.getResourceAsReader("config.xml"); SqlSessionFactory sessionFactory=new SqlSessionFactoryBuilder().build(reader); SqlSession session=sessionFactory.openSession(); IStudentDao iStudentDao=session.getMapper(IStudentDao.class); Map<String,Object> map=new HashMap<>(); map.put("homeAddress","sy"); map.put("schoolAddress","sy"); List<Student> stus = iStudentDao.selectStudentByhomeOrSchoolMap(map); System.out.println(stus); session.close(); reader.close(); }
(1)用map中的key的值 匹配 占位符#{stuAge} ,如果匹配成功,就用map的value替换占位符
.2)mybatis如何调用存储过程
1.示例一:查询某个的学生总数
输出:该年级的总数
1.1 在数据库创建存储过程
DELIMITER // CREATE PROCEDURE queryByGradeWithProcedure (IN gName VARCHAR(30),OUT scount INT) BEGIN SELECT COUNT(1) INTO scount FROM student WHERE graName=gName; END //
1.2 如何调用数据库里面的存储过程呢?
<!-- 通过调用存储过程 实现查询 ,statementType="CALLABLE" 存储过程的输入参数一般使用HashMap来传递 --> <select id="queryCOuntByGraNameWithProcedure" statementType="CALLABLE" parameterType="HashMap"> {call queryByGradeWithProcedure( #{gName,mode=IN}, #{scount,mode=OUT,jdbcType=INTEGER})} </select>
其中 通过statementType="CALLABLE" 设置SQL的执行方式是存储过程
存储过程的输入参数是gName 需要通过HashMap来指定
通过HashMap方法的put方法传入输出参数的值,通过HashMap的get方法来获取输出参数的值
存储过程 无论输入参数是什么值,语法上都需要 用map来传值
1.3测试类
public static void selectOneStudentByGraName() throws IOException { Reader reader = Resources.getResourceAsReader("config.xml"); SqlSessionFactory sessionFactory=new SqlSessionFactoryBuilder().build(reader); SqlSession session=sessionFactory.openSession(); IStudentDao iStudentDao=session.getMapper(IStudentDao.class); Map <String,Object> map=new HashMap<>(); map.put("gName","S2"); iStudentDao.queryCOuntByGraNameWithProcedure(map); //获取存储过程的输出参数 Object count=map.get("scount"); System.out.println(count); session.close(); reader.close(); }
2.示例二:根据学号删除学生
输入:学号
2.1 创建存储过程
DELIMITER // CREATE PROCEDURE deleteStudentByStuno (IN NO INT ) BEGIN DELETE FROM student WHERE stuno=NO; END //
2.2 调用存储过程
<!-- 通过调用存储过程 按照id值删除学号--> <delete id="deleteStudentByno" statementType="CALLABLE" parameterType="HashMap"> {call deleteStudentByStuno( #{no,mode=IN})} </delete>
public static void deleteStudentByno() throws IOException { Reader reader = Resources.getResourceAsReader("config.xml"); SqlSessionFactory sessionFactory=new SqlSessionFactoryBuilder().build(reader); SqlSession session=sessionFactory.openSession(); IStudentDao iStudentDao=session.getMapper(IStudentDao.class); Map <String,Object> map=new HashMap<>(); map.put("no",3); iStudentDao.deleteStudentByno(map); session.commit(); session.close(); reader.close(); }