1. myBatis choose when:条件查询,以前不太清楚它的含义,都是使用if判断,或在程序里判断,使用了之后,发觉有些场景下还是挺不错的。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23场景1:默认排序 <choose> <when test="sortName != null and sortType != null"> ORDER BY ${sortName} ${sortType} </when> <otherwise> ORDER BY order_create_time DESC </otherwise> </choose> 场景2:通过一个字段判断是否支持模糊查询 <choose> <when test="isLike != null and isLike !=''"> <if test="sellerName != null"> seller_name like #{sellerName,jdbcType=VARCHAR} and </if> </when> <otherwise> <if test="sellerName != null"> seller_name = #{sellerName,jdbcType=VARCHAR} and </if> </otherwise> </choose>
2. mybatis的sum()函数返回类型是BigDecimal类型,所以我们处理的时候需要注意下:
1> 返回 Object 值,然后通过 Integer.parseInt(obj.toString()); 来得到int值;
2> 返回 BigDecimal 值,然后通过 BigDecimal.intValue()得到需要的值,应该说我们推荐使用第二种方法。
3> 如果指定resultType为Long类型的话,则不用考虑BigDecimal;
1
2
3
4
5<select id="selectByParams" resultType="java.util.Map" parameterType="java.util.Map"> select sum(amount) as amountTotal,company_id as companyId from test <include refid="selectByParamsWhere" /> </select>
3. 同理,mybatis的count()函数返回类型是Long;
4. mybatis的#{} 和 ${}的不同场景,或者说区别:
1) #{},预编译SQL时,会将传入的数据都当成一个字符串,会对自动传入的数据加一个引号; ${}仅仅是文本替换。如:
1select * from student order by #{stuId}
1select * from student order by 'stu_id'
1select * from student order by ${stuId}
1select * from student order by stu_id
1
2
3<if test=" offset != null and limit != null"> limit ${offset}, ${limit} </if>
1select * from ${tableName} where id = #{name}
1user; delete user; --
1select * from user; delete user; -- where name = ?;
4) 直接接受从用户传入的内容并直接访问数据库,这种做法是不安全的。这会导致潜在的SQL注入攻击,因此不应该允许用户输入的数据直接访问数据库,应该对输入的数据自行转义并检查。
5. mybatis在查询的时候,如果返回的是map而不是实体对象的话,map中的value如果为null的话,那这个字段就没有返回,这样的话可能会有空指针的出现;
1) 一种方式就是不返回map,返回实体对象,然后映射一下;
2) 另一种方式,网上说的,不过还没验证过;
1
2
3
4
5在mybatis的配置文件中加入,mybatis必须3.2版本以上 <settings> <setting name="cacheEnabled" value="true"/> <setting name="callSettersOnNulls" value="true"/> </settings>
3) 调用到这个接口的地方进行非空判断;
最后
以上就是精明网络最近收集整理的关于Mybatis使用过程中的一些总结的全部内容,更多相关Mybatis使用过程中内容请搜索靠谱客的其他文章。
发表评论 取消回复