用基本數據類型傳參,只能傳入一個參數。經過#{參數名}便可獲取傳入的參數值。java
經過#{java實體類的屬性名},#{map的KeyName}便可獲取傳入的值。數組
能夠傳遞一個List實例或者一個數組做爲參數對象傳給MyBatis,當你這麼作的時候,MyBatis會自動將它包裝在一個Map中,若是傳入的是List,將使用"list"做爲鍵,若是傳入的是數組,將以"array"做爲鍵。app
要迭代一個集合,使用foreach,它能夠指定一個集合,聲明集合項和索引變量,也能夠指定開放和關閉的字符串、分隔符。dom
注意:當想要傳入collection時,並不能直接傳入。由於Mybatis生成SQL語句遍歷list時,是須要用到get()方法的,而Collection中沒有get方法,參見MyBatis官方文檔中「動態SQL」。this
List<User> selectByExample(UserExample example);
<where> <foreach collection="oredCriteria" item="criteria" separator="or" > <if test="criteria.valid" >
此時collection="oredCriteria"會找到入參example這個非集合對象的oredCriteria屬性,此屬性是一個集合code
#示例xml
public List<StudentEntity> getStudentListByClassIds_foreach_list(List<String> classIds);
<select id="getStudentByClassIds_foreach_list" resultMap="resultMap_studentEntity"> SELECT ST.STUDENT_ID, ST.STUDENT_NAME, ST.STUDENT_SEX, ST.STUDENT_BIRTHDAY, ST.STUDENT_PHOTO, ST.CLASS_ID, ST.PLACE_ID FROM STUDENT_TBL ST WHERE ST.CLASS_ID IN <foreach collection = "list" item="classIdList" open="(" separator="," close=")"> #{classIdList} </foreach> </select>
collection="list"這是默認寫法,入參爲數組Integer[] idarr,則用collection="array"。MyBatis會默認找到那個list屬性。對象
@Test public void test7_2_foreach() { ArrayList<String> classIdList = new ArrayList<String>(); classIdList.add("20000001"); classIdList.add("20000002"); List<StudentEntity> list = this.dynamicSqlMapper.getStudentListByClassIds_foreach_list(classIdList); for (StudentEntity e : list) { System.out.println(e.toString()); } }
<select id="selectTeacher" parameterType="com.myapp.domain.Teacher" resultType="com.myapp.domain.Teacher"> select * from Teacher where c_id=#{id} </select>
<select id="findTeacherByPage"resultMap="supervisorResultMap" parameterType="java.util.Map"> select * from teacher where title like #{title} order by ${sort} ${dir} limit #{start},#{limit} </select>
public List<Teacher> findTeacherByPage(Map<String, Object> map); Map<String, Object> params = new HashMap<String, Object>(); //以name字段升序排序, params.put("sort", "name"); params.put("dir", "asc"); //查詢結果從第0條開始,查詢2條記錄 params.put("start", 0); params.put("limit", 2); //查詢職稱爲教授或副教授的教師 params.put("title", "%教授");
此時入參map的key至關於一個object的屬性名,value至關於屬性值排序
使用@Param註解。索引
public List<Teacher> selectTeacher(@Param(value="id") String id,@Param(value="sex") String sex);
<select id="selectTeacher" resultType="com.myapp.domain.Teacher"> select * from Teacher where c_id=#{id} and sex=#{sex} </select>
List<Teacher> tList = teacherMapper.selectTeacher("2","男");