Mybatis作为半自动化的SQL,为我们提供了非常大的便利。
1.#{}和${}的区别???
{}是占位符,预编译处理;${}是拼接符,字符串替换,没有预编译处理。
Mybatis在处理#{}时,#{}传入参数是以字符串传入,会将SQL中的#{}替换为?号,调用PreparedStatement的set方法来赋值。
Mybatis在处理时,是原值传入,就是把 {}时,是原值传入,就是把时,是原值传入,就是把{}替换成变量的值,相当于JDBC中的Statement编译
变量替换后,#{} 对应的变量自动加上单引号 ‘’;变量替换后,${} 对应的变量不会加上单引号 ‘’
{} 可以有效的防止SQL注入,提高系统安全性;${} 不能防止SQL 注入
{} 的变量替换是在DBMS 中;${} 的变量替换是在 DBMS 外
2.怎么写模糊查询Like语句???
(1)'%${question}%' 可能引起SQL注入,不推荐
(2)"%"#{question}"%" 注意:因为#{…}解析成sql语句时候,会在变量外侧自动加单引号’ ',所以这里 % 需要使用双引号" ",不能使用单引号 ’ ',不然会查不到任何结果。
(3)CONCAT(’%’,#{question},’%’) 使用CONCAT()函数,推荐
(4)使用bind标签
<select id="getList" resultType="com.wang.pojo.Blog">
<bind name="pattern" value="'%' + title + '%'" />
select id,title,content,comment from blog where title LIKE #{pattern}
</select>
3.顺序传递传参方法
public Blog selectBlog(String title, int id);
<select id="selectBlog" resultMap="BlogResultMap">
select * from blog
where title = #{0} and id = #{1}
</select>
4.Map传递参数方法
public Blog selectBlog(Map<String, Object> params);
<select id="selectBlog" parameterType="java.util.Map" resultMap="BlogResultMap">
select * from blog
where title = #{title} and id = #{id}
</select>
5.使用较多的Java Bean传参法
public Blog selectBlog(Blog blog);
<select id="selectBlog" parameterType="com.wang.pojo.Blog" resultMap="BlogResultMap">
select * from blog
where title = #{title} and id = #{id}
</select>
评论