2019/12/10 学习笔记
mybatis排序无效
首先贴代码:
<!-- 分页查询用户 -->
<select id="queryStudentsBySql" resultMap="bookResult">
select * FROM book order by #{sort} limit #{currIndex} , #{pageSize}
</select>
是不是看上去没什么问题,先排序,然后分页。
其实不然,对于形如#{variable} 的变量,Mybatis会将其视为字符串值,在变量替换成功后,缺省地给变量值加上引号
因为#{}里面的东西会自动加一个“”,所以在mysql里面得到的就是
order by “id” 这种,所以应该把#{sort}改成${sort}
<!-- 分页查询用户 -->
<select id="queryStudentsBySql" resultMap="bookResult">
select * FROM book order by ${sort} limit #{currIndex} , #{pageSize}
</select>
这样就能正确查询了。
select设置默认值
一种最简单粗暴的就是;
<select id="sort-by" name="sort-by" class="form-control" >
<option ${sort == "bid" ?"selected= 'selected'" : ""}value="bid">默认</option>
<option ${sort == "convert(bname using gbk)" ?"selected= 'selected'" : ""}value="convert(bname using gbk)">书名</option>
<option ${sort == "price" ?"selected= 'selected'" : ""}value="price">价格</option>
</select>
意思就是根据条件判断是不是设置为默认。