在我们操作MyBatis的时候,sql语句 输入参数时,需要用#{xx} 或 ${xx} 来传值
例如查学生Id:
<select id="queryStudentBySno" resultType="Student" parameterType="int">
select * from Student where id = #{id}
</select>
或者
<select id="queryStudentBySno" resultType="Student" parameterType="int">
select * from Student where id = ${value}
</select>
那么两者有什么区别呢?
a.当输入参数为8个基本类型+String的时候
#{任意值} 而 ${value} (只能写value)
b.#{} 会自动给String类型加上 ‘ ’ (自动类型转换)
而 ${} 则原样输出,但是适合于 动态排序(动态字段)
c.#{} 可以防止Sql注入 ${} 不行
下面我们来具体实现动态排序:
首先什么是动态排序 大致可以理解为:
我们既可以 根据 id 排序 也可以根据 name ,age 等其他字段排序。
xml配置文件
<select id="queryStudentOrderByColumn" parameterType="string" resultType="Person">
select * from Person order by ${value} desc
</select>
方法:
//查询并 根据字段动态排序
public static void queryStudentOrderByColumn() throws IOException {
Reader reader = Resources.getResourceAsReader("config.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
SqlSession session = sqlSessionFactory.openSession();
/* 1.实现接口
* 2.然后接口文件的名称 与 xml中的namespace形成映射 自动绑定配置
*/
StudentMapper studentmapper = session.getMapper(StudentMapper.class);
List<Person> persons = studentmapper.queryStudentOrderByColumn("id");
System.err.println(persons);
session.close();
}
测试
public static void main(String[] args) throws IOException {
queryStudentOrderByColumn();
}
然后就实现了根据Id 倒序排列。当需要其他排序方式时,我们只需要修改传入方法的参数即可。