不同之处
#{} | ${} | |
---|---|---|
简单类型(8个基本类型和String) | #{xx}xx可以随便写 | ${value} 其中的标识符只能是value |
对象类型(都必须是属性名) | #{属性名} | ${属性名} |
sql注入 | .#{}可以防止SQL注入 | ${}不防止 |
对于String的处理 | 自动给String加上’ ’ | ${} 原样输出 |
关于String:
#{}会自动给String类型加上’ ’ (也可以称之为自动类型转换)
${} 原样输出,但是适合于 动态排序(动态字段)
比如如果要查询String的话:
select stuno,stuname,stuage from student where stuname = #{value}
select stuno,stuname,stuage from student where stuname = '${value}'
关于动态排序问题:
如果我们需要对表中的字段进行排序:
select stuno,stuname,stuage from student order by ${value} asc
这个地方原本的sql语句就是没有‘ ’的,如果用上#会自动加上‘ ’,反倒不能用了
只能用${}
相同之处:
i.获取对象值:
方式一是把%%加到java代码当中
方式二是吧%%加到sql语句当中
模糊查询,方式一:
select stuno,stuname,stuage from student where stuage= #{stuAge} or stuname like #{stuName}
Student student = new Student();
student.setStuAge(24);
student.setStuName("%w%");//手动加上% %
List<Student> students = studentMapper.queryStudentBystuageOrstuName(student) ;
模糊查询,方式二:
select stuno,stuname,stuage from student where stuage= #{stuAge} or stuname like '%${stuName}%'
student.setStuName("w");
ii.获取嵌套类型对象(类中类)
就是在实体类当中还有一个class
Student中有个address类,address中有homeAdress和schoolAddress
不用类中类传入参数:
<select id="queryStudentByaddress" parameterType="address" resultType="student" >
select stuno,stuname,stuage from student where homeaddress = #{homeAddress} or schooladdress = '${schoolAddress}'
</select>
使用类中类:
<!-- 输入参数为 级联属性 -->
<select id="queryStudentByaddress" parameterType="student" resultType="student" >
select stuno,stuname,stuage from student where homeaddress = #{address.homeAddress} or schooladdress = '${address.schoolAddress}'
</select>