输入参数parameterType
一、#{},${}的区别:
1、类型为简单类型(8个基本类型+String):
#{任意标识符}
${value},标识符只能是value,否则会出错。
类型为对象:
#{属性名}
${属性名}
2、#{}自动给String加上单引号’’(自动类型转换)
${}原样输出,需要人为加上单引号,即 ’ ${value}’
<select id="selectStudentByStuName" parameterType="String" resultType="org.ec.entity.Student">
<!-- select * from studentMybatis where stuName=#{stuName} -->
select * from studentMybatis where stuName='${value}'
</select>
$ {value}更适合用于动态排序,#{xxx}会自动加上单引号,相当于按照 ‘xxx’ 排序(按照stuName排序,但实际却是 ‘stuName’ ),所以要用${value}
<select id="testselectStudentOrderByColumn" parameterType="String" resultType="org.ec.entity.Student">
select * from studentMybatis order by ${value} desc
</select>
3、#{}可以防止SQL注入
${}不防止
二、#{},${}的相同之处:
1):都可以获取对象的值
使用#{}:
传值方式:
Student student = new Student(2,"%张%",29);
//mapper.xml
<select id="selectStudentByStuNoOrStuName" parameterType="org.ec.entity.Student" resultType="org.ec.entity.Student">
select * from studentMybatis where stuNo = #{stuNo} or stuName like #{stuName}
</select>
传入的字符串为%张%,经过#{}自动加引号变为’%张%’,SQL语句为:select * from studentMybatis where stuNo =‘stuNo’ or stuName like ‘%stuName%’
使用${}:
传值方式:
Student student = new Student(2,"张",29);
//mapper.xml
<select id="selectStudentByStuNoOrStuName" parameterType="org.ec.entity.Student" resultType="org.ec.entity.Student">
select * from studentMybatis where stuNo = #{stuNo} or stuName like '%${stuName}%'
</select>
三、输入参数为嵌套类型
输入参数为Address类,Address类中有两个属性。
Student类是属性:
private int stuNo;
private String stuName;
private int stuAge;
private Address address;//同时包含家庭和学校
Address类的属性:
private String homeadd;
private String schooladd;
mapper.xml中的SQL语句:
<select id="selectStudentByAddress" parameterType="org.ec.entity.Address" resultType="org.ec.entity.Student">
select * from studentMybatis where homeadd = #{homeadd} or schooladd = '${schooladd}'
</select>
<select id="selectStudentByAddressJJ" parameterType="org.ec.entity.Student" resultMap="selectStudentByAddressJJ">
select * from studentMybatis where homeadd = #{address.homeadd} or schooladd = '${address.schooladd}'
</select>
<resultMap type="org.ec.entity.Student" id="selectStudentByAddressJJ">
<!--把数据库中homeadd,schooladd放入address变量中-->
<result property="address.homeadd" column="homeadd"/>
<result property="address.schooladd" column="schooladd"/>
</resultMap>
四、输入参数为HashMap
用Map中的key匹配占位符#{stuAge},如果匹配成功就用Map中的value替换占位符。
//mapper.xml
<select id="selectStudentWithHashMap" parameterType="HashMap" resultType="org.ec.entity.Student">
select * from studentMybatis where stuAge=#{stuAge} or stuName like '%${stuName}%'
</select>
//测试部分
@Test
public void testselectStudentWithHashMap() {
Map<String,Object> studentMap = new HashMap<>();
studentMap.put("stuAge", 29);
studentMap.put("stuName", "张");
StudentMapper mapper = new StudentMapperImpl();
List<Student> students = mapper.selectStudentWithHashMap(studentMap);
for(Student s:students)
System.out.println(s);
}