提问人:m4mmt 提问时间:11/16/2023 最后编辑:m4mmt 更新时间:11/19/2023 访问量:44
使用 MyBatis mapper.xml 在 Postgresql 的 JSONB 字段内的同一查询中递增多个计数器
Using MyBatis mapper.xml to increment a multiple counters in the same query inside of a JSONB field in Postgresql
问:
我正在使用 Java + Spring + MyBatis + Postgresql。我有一个表,其中有一列(在 Java 中映射到),出于性能原因,我想使用相对于属性所属实体的查询进行更新。JSONB
BIGINT
Long
mapper.xml
假设我具备以下要素:
table_a
:数据库表column_1
:类型的列table_a
JSONB
key_alpha
:与值关联的字段column_1
BIGINT
理想情况下,在纯语法中,我会执行以下操作来初始化此类值:psql
UPDATE table_a
SET column_1 = jsonb_set(column_1, '{key_alpha}', to_jsonb(0));
并按以下方法递增它:
UPDATE table_a
SET column_1 = jsonb_set(column_1, '{key_alpha}', to_jsonb((column_1->>'key_alpha')::bigint + 1));
问题在于,这个语法看起来与 MyBatis 映射器语法不兼容。我怎样才能使用 MyBatis 或替代方法实现这个结果,同时记住我需要一个性能关键的方法?xml
更具体地说,如果我尝试在以下情况下使用此语法:mapper.xml
<if test="incrementCountAlpha != null">column_1 = jsonb_set(column_1, '{key_alpha}', to_jsonb((column_1->>'key_alpha')::bigint + #{incrementCount})),</if>
<if test="incrementCountBeta != null">column_1 = jsonb_set(column_1, '{key_beta}', to_jsonb((column_1->>'key_beta')::bigint + #{incrementCount})),</if>
我收到以下错误;### Error updating database. Cause: org.postgresql.util.PSQLException: ERROR: multiple assignments to same column "column_1"
答:
0赞
ave
11/19/2023
#1
以下语句应该可以实现您的目标。
<update id="updateColumn1">
update table_a set column_1 = column_1
<if test="incrementCountAlpha != null">
|| jsonb_build_object(
'key_alpha',
coalesce((column_1->>'key_alpha')::bigint, 0) + #{incrementCountAlpha})
</if>
<if test="incrementCountBeta != null">
|| jsonb_build_object(
'key_beta',
coalesce((column_1->>'key_beta')::bigint, 0) + #{incrementCountBeta})
</if>
</update>
COALESCE
如果保证事先初始化目标字段,则可能没有必要。
下面是一个可执行的演示项目:
https://github.com/harawata/mybatis-issues/tree/master/so-77490757
评论
column_1