事情是这样的,有一个接口需要一个倒序排序返回,一个简单的CURD
伪代码
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="runstatic.cloudexamples.cloudwebexample.mapper.MessageMapper">
<insert id="queryAllDesc" parameterType="runstatic.cloudexamples.cloudwebexample.entity.Message">
select *
from message
order by #{fieldName} desc
</insert>
</mapper>
package runstatic.cloudexamples.cloudwebexample.mapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import runstatic.cloudexamples.cloudwebexample.entity.Message;
import java.util.List;
/**
* @author chenmoand
*/
@Mapper
public interface MessageMapper {
List<Message> queryAllDesc(String fieldName);
}
在调用queryAllDesc("create_time")
后本来的意思是按照开始时间,越新创建的越靠前,结果查询到的排序结果并没有生效,sql实际上被mybatis解析成了
select * from message
order by 'create_time' desc
因为mybatis #{}, 在sql 中 'create_time’是一个字符串而create_time是列名,因为每次都是按照一个固定的字符串排序,不管怎么排都不会生效,应该使用 ${},修改后
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="runstatic.cloudexamples.cloudwebexample.mapper.MessageMapper">
<insert id="queryAllDesc" parameterType="runstatic.cloudexamples.cloudwebexample.entity.Message">
select *
from message
order by ${fieldName} desc
</insert>
</mapper>
总结: 使用#{}更加安全,但有些时候也需要使用{}的同时也要注意SQL注入问题