1. SQL in , foreach
1.1Mybatis
<select id="countByUserList" resultType="_int" parameterType="list">
select count(*) from users
<where>
id in
<foreach item="item" collection="list" separator="," open="(" close=")" index="">
#{item.id, jdbcType=NUMERIC}
</foreach>
</where>
</select>
1.2 Bee
select count(*) from users where id in #{list @in}
定义一个list参数(可支持List,Set类型)传入即可.
可将
<foreach item="item" collection="list" separator="," open="(" close=")" index="">
#{item.id, jdbcType=NUMERIC}
</foreach>
替换为: #{list @in} 即可. 无需指定多余的信息,更无需指定jdbcType.
2. 批量插入(Bee无需foreach)
2.1Mybatis
<insert id="batchSave">
insert into user(name, password) values
<foreach collection="list" item="user" separator=",">
(#{user.name}, #{user.password})
</foreach>
</insert>
2.2 Bee
sql :
insert into user(name, password) values (#{name}, #{password})
Bee无需foreach多余配置;
Java代码,如下, 只需定义好多行数据传入即可.
preparedSql.insertBatch(sql, parameterMapList);
3. Bee @toIsNULL1,@toIsNULL2
select * from orders where userid=#{userid@toIsNULL1}
当userid为null时,会转成
select * from orders where userid is null
避免了where userid=null的错误.
4. like用法.
4.1 Mybatis
有是预编译和不是预编译之分,有#和$之分,还有绑定变量的概念,加重使用者负担.
select * from person where name like "%"#{name}"%"
select * from person where name like '%'||#{name}||'%'
select * from person where name like '%${name}%'
三种写法对比后,第一种属于预编译SQL,后两种都不是,因此推荐使用第一种写法。
MySQL可以使用CONCAT函数。例:
<if test="userName != null and userName != ''">
and user_name like concat('%', #{userName}, '%')
</if>
注意:使用CONCAT函数连接字符串,在 MySQL 中,这个函数支持多个参数,但在 Oracle 中只支持两个参数。
针对这种情况,可以使用 bind 标签来避免由于更换数据库带来的一些麻烦。将上面的方法改为 bind 方式后,代码如下:
<if test="userName != null and userName != ''">
<bind name="userNameLike" value="'%' + userName + '%'"/>
and user_name like #{userNameLike}
</if>
bind 标签的两个属性都是必选项,name 为绑定到上下文的变量名,value 为 OGNL 表达式。
4.2 Bee like使用简单 一看就懂.
#{%name} , #{name%}, #{%name%}
左匹配,右匹配,还是左右匹配, 直接将%放到变量名旁边即可.
关键是Bee转换的sql都是安全的,免受攻击的. 没有坑!
select * from orders where name like #{name%}
select * from orders where name like #{%name}
select * from orders where name like #{%name%}
详细用法:
https://blog.youkuaiyun.com/abckingaa/article/details/123582877
Bee的like用法,不用bind绑定,都可以防止注入攻击_abckingaa的博客-优快云博客
Bee,互联网新时代的Java ORM工具,更快、更简单、更自动,开发速度快,运行快,更智能!
Bee让程序员/软件工程师,从手工编码中解放出来,Bee更适合智能软件制造时代!
十分钟即可入门!
立志做最懂用户的软件!