Mybatis postgres 使用汇总

# ? 区别

#{}

使用#{}意味着使用的预编译的语句,即在使用jdbc时的preparedStatement,sql语句中如果存在参数则会使用?作占位符,我们知道这种方式可以防止sql注入,并且在使用#{}时形成的sql语句,已经带有引号,例,select * from table1 where
id=#{id} 在调用这个语句时我们可以通过后台看到打印出的sql为:select * from table1 where id='2' 加入传的值为2.也就是说在组成sql语句的时候把参数默认为字符串。

${}

使用${}时的sql不会当做字符串处理,是什么就是什么,如上边的语句:select * from table1 where id=${id} 在调用这个语句时控制台打印的为:select * from table1 where id=2 ,假设传的参数值为2。

总结

从上边的介绍可以看出这两种方式的区别,我们最好是能用#{}则用它,因为它可以防止sql注入,且是预编译的,在需要原样输出时才使用${}

 

foreach标签内传入list为空的解决

 问题语句

SELECT * FROM table_xxx (NOLOCK)
WHERE id in
  <foreach collection="list" index="index" item="item"  open="(" separator="," close=")">  
    #{item}
  </foreach>

解决

SELECT * FROM table_xxx (NOLOCK) 
WHERE  isActive=1
<foreach collection="list" index="index" item="item" open="AND id IN (" separator="," close=")">
    #{item}
</foreach>

 

postgres conflict 保存或更新

类似于mysql中的REPLACE

<foreach collection="datas" item="item" separator=";">
    insert into tablename(
    id,
    name
    ) values(
        #{item.id},
        #{item.name}
    ) on conflict (id) do update set
        name=#{item.name}
</foreach>

批量插入

<insert id="addUser" parameterType="java.util.List" >
  insert into user(name,age) values
    <foreach collection="list" item="item" index="index" separator=",">
        (#{item.name},#{item.age})
    </foreach>
</insert>

 

传入一个集合A,返回A中不在数据库表中的数据

<choose>
    <when test="set != null and set.size != 0">
        select v.val FROM
        <foreach collection="set" item="s" separator="union" open="(" close=")">
            select #{s} as val
        </foreach>
        v where v.val not IN (select xx from XX_table where xxxx='xxxxxx')<!-- select 自定 -->
    </when>
    <otherwise>
        select val from module where 1!=1
    </otherwise>
</choose>

 

参考

https://yaxing97.com/mybatis-batch-insert/

https://blog.csdn.net/Sibylsf/article/details/108650932

posted @ 2023-07-06 09:36  jihite  阅读(149)  评论(0编辑  收藏  举报