1.输入参数为简单类型(8个基本类型+String类型)
此时#{},里面可以写任意值,但是我们一般指定数据库表中的列名
<select id="queryStudentByStuno" useCache="false" parameterType="int" resultMap="studentMapping" >
select * from student2 where stuno = #{stuNo}
</select>
如果是${} ,里面必须写value
2.输入参数为对象类型
#{} ${},里面必须为属性名
<select id="queryStudentBystuAgeorstuName" parameterType="student" resultType="student" >
select stuno,stuname,stuage from student2 where stuage=#{stuAge} or stuname like '%${stuName}%'
</select>
对于字符串类型,#{}会自动给字符串加上' ' ${}则是原样输出,不会自动添加' ',但是${}适合于动态排序
select stuno,stuname,stuage from student where stuname = #{value}
select stuno,stuname,stuage from student where stuname = '${value}'
动态排序
<select id="queryStudentOrderByColumn" parameterType="string" resultType="student" >
select * from student2 order by ${value} desc
</select>
#{}可以防止sql注入,${}不可以
#{}和${}的相同之处,都可以获取对象的值(嵌套类型对象)
<select id="queryStudentBystuAgeorstuName" parameterType="student" resultType="student" >
select stuno,stuname,stuage from student2 where stuage=#{stuAge} or stuname like '%${stuName}%'
</select>
嵌套类型对象
<!-- 嵌套地址,参数不传address,传student,输入参数为级联属性 -->
<select id="queryStudentByaddress" parameterType="student" resultType="student" >
select * from student2 where homeaddress=#{address.homeAddress} or schooladdress='${address.schoolAddress}'
</select>
Student类中有一个Address类的属性address,里面的两个属性homeAddress和schoolAddress就可以这样获取
输入参数为HashMap类型
mapper接口中定义方法:
List<Student> queryStudentBystuAgeorstuNameWithHashMap(Map<String, Object> map);
mapper.xml中写sql:
<!-- 输入参数为haspmap -->
<select id="queryStudentBystuAgeorstuNameWithHashMap" parameterType="HashMap" resultType="student" >
select * from student2 where stuage=#{Age} or stuname like '%${Name}%'
</select>
用map中key的值去匹配#{Age},${Name},保证key和占位符一样。如果"Age"和#{Age}匹配成功,
则将value值23替换进去,即where stuage=23.
StudentMapper studentMapper = session.getMapper( StudentMapper.class) ;
Map<String, Object> studentMap=new HashMap<String, Object>();
studentMap.put("Age", 23);
studentMap.put("Name", "w");
List<Student> students = studentMapper.queryStudentBystuAgeorstuNameWithHashMap(studentMap) ;//接口的方法->SQL
System.out.println(students);
session.close();
这样测试就能成功,拿到值