提出问题
查询语句一般会用到排序 order by ,有时排序是由前台页面决定的,比如:根据 姓名排序、生日排序,此时 order by 就不能写在 mapper.xml中
解决问题
在 mapper.xml中,可以通过 ${} 将传入的字符串,拼接 到sql中,如下:
public interface UserMapper {
List<User> getAllUsers(@Param("order_by")String order_by);
}
对应的 XML 定义如下:
<select id="select" resultType="top.malaoshi.entity.User">
select * from user
<if test="order_by!=null and order_by!=''">
order by ${order_by}
</if>
</select>
将传入的 order_by ,拼接到 sql中
${} 与 #{} 区别
${} 是将传入的内容 拼接 到sql中
#{} 会翻译成 占位符 ? ,然后绑定参数