文章目录
mybaits动态sql
if
如果name不为空,就进行拼接if体
<if test="bname != null" >
#{bname,jdbcType=VARCHAR},
</if>
trim
trim则是去空格。
<trim prefix="values (" suffix=")" suffixOverrides="," >
<if test="bid != null" >
#{bid,jdbcType=INTEGER},
</if>
<if test="bname != null" >
#{bname,jdbcType=VARCHAR},
</if>
<if test="price != null" >
#{price,jdbcType=REAL},
</if>
</trim>
foreach
collection 对应的是你要遍历的集合,这里我是从接口那边定义传过来的。
open 是当循环开始时在前面加的字符。
close 是当循环结束时在后面加的字符。
separator 是使用什么隔开。
item 则是代表着集合中的每个元素。
<foreach collection="bookIds" open="(" close=")" separator="," item="bid">
#{bid}
</foreach>
模糊查询
接口
// 模糊查询三种方法
List<Book> selectBylike1(@Param("bname") String bname);
List<Book> selectBylike2(@Param("bname") String bname);
List<Book> selectBylike3(@Param("bname") String bname);
xml配置
<!-- 模糊查询三种方法-->
<select id="selectBylike1" resultType="com.tzp.model.Book" parameterType="java.lang.String">
select * from t_mvc_book where bname like #{bname}
</select>
<select id="selectBylike2" resultType="com.tzp.model.Book">
select * from t_mvc_book where bname like '${bname}'
</select>
<select id="selectBylike3" resultType="com.tzp.model.Book">
select * from t_mvc_book where bname like concat(concat('%',#{bname}),'%')
</select>
测试
public void selectBylike() {
List<Book> bb = this.bookService.selectBylike1(StringUtils.toLikeStr("圣墟"));
// List<Book> bb = this.bookService.selectBylike2(StringUtils.toLikeStr("圣墟"));
// List<Book> bb = this.bookService.selectBylike3(StringUtils.toLikeStr("圣墟"));
for (Book book : bb) {
System.out.println(book);
}
}
mybaits里面的 #传参与 $ 传参有什么区别?
也是就是上面的第一种的方法和第二种方法的区别
-
#将传入的数据都当成一个字符串,会对自动传入的数据加一个双引号。
如:order by #user_id#,如果传入的值是111,那么解析成sql时的值为order by ‘111’,
如果传入的值是id,则解析成的sql为order by “id”. -
$将传入的数据直接显示生成在sql中。
如:order by u s e r i d user_id userid,如果传入的值是111,那么解析成sql时的值为order by user_id,
如果传入的值是id,则解析成的sql为order by id. -
#方式能够很大程度防止sql注入。
-
$方式无法防止Sql注入。
-
$方式一般用于传入数据库对象,例如传入表名.
-
一般能用#的就别用$.
查询返回结果集的处理
resultMap:适合使用返回值是自定义实体类的情况
resultType:适合使用返回值的数据类型是非自定义的,即jdk的提供的类型
在第一种方法中就使用了这个BaseResultMap
<resultMap id="BaseResultMap" type="com.cpc.model.User" >
<constructor >
<idArg column="id" jdbcType="INTEGER" javaType=