1. 程式人生 > >MyBatis實現查詢結果按照查詢引數的順序排序

MyBatis實現查詢結果按照查詢引數的順序排序

查詢id為指定id的學生集合。

查詢引數為list,即學生id的集合,list泛型為Integer,比如list中的元素為151,208,4,118,109,正常的查詢,返回的list結果集,遍歷學生id放在另一個list結果集中,也就是查詢結果學生id的集合為4,109,118,151,208。

<select id="getStudentListByIdList" parameterType="java.util.List" resultMap="studentResultMap">
  	select id,name,gender,age
  	from t_student
  	where id in
  		<foreach collection="list" open="(" separator="," close=")" item="id">
  			#{id}
  		</foreach>
  </select>

如果新增以下程式段(即order by),那麼返回的list結果集,取學生id組成一個集合,那麼這個id集合的元素順序和引數list中的元素順序是一樣的,也就是151,208,4,118,109。

<select id="getStudentListByIdList" parameterType="java.util.List" resultMap="studentResultMap">
  	select id,name,gender,age
  	from t_student
  	where id in
  		<foreach collection="list" open="(" separator="," close=")" item="id">
  			#{id}
  		</foreach>
  	order by field(
  		id,
  		<foreach collection="list" separator="," item="id">
  			#{id}
  		</foreach>
  	)
  </select>