1、單個參數時
此時sqlMapper中的配置
或者
都可以;因為參數只有一個,不會混亂,只有單個參數時紅框中的取名可隨意
2、多個參數時
mapper接口中的方法:
sqlmapper中的配置:
<!-- 多個參數時,mybatis會做特殊處理;多個參數會被封裝成一個map key:param1,param2,.......paramN value:傳入的參數值 #{ }就是從map中獲取指定key的值 --> <select id="selectEmpByIdAndName" resultType="employee"> select * from employee where id = #{param1} and name = #{param2} </select>
3、多個參數時(命名參數方式)
mapper接口中的方法:利用@Param配置進行命名參數
sqlmapper中的配置:
<!-- 多個參數命名方式 --> <select id="selectEmpByIdAndName" resultType="employee"> select * from employee where id = #{id} and name = #{name} </select>
4、參數為POJO類
mapper接口中的方法:
sqlmapper中的配置:
#{屬性名}:取出傳入的pojo的對應屬性值
<insert id="addEmp" parameterType="employee" > insert into employee(name,gender) values(#{name},#{gender}) </insert>
5、如果多個參數不是業務模型中的數據,沒有對應的pojo,(這些參數不經常使用的前提下)為了方便,也可以直接傳入map(不用@Param注解時,mybatis默認把多個參數封裝在一個map中),自己封裝可以指定key值;可以和上面第二點對比
mapper接口中的方法:
sqlmapper中的配置
<select id="selectEmpByIdAndName" resultType="employee"> select * from employee where id = #{idtest} and name = #{nametest} </select>
測試方法中傳入map
@Test public void test3() throws IOException { String source = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(source); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); //獲取sqlSession實例,能直接執行映射的sql語句 SqlSession sqlSession = sqlSessionFactory.openSession(); EmployeeMapper employeeMapper = sqlSession.getMapper(EmployeeMapper.class); Map map = new HashMap(); map.put("idtest", 1); map.put("nametest", "xiaohon"); Employee employee = employeeMapper.selectEmpByIdAndName(map); System.out.println(employee); sqlSession.close(); }