简体   繁体   English

如何在Spring JDBC中使用MERGE语句插入/更新单个记录

[英]How to insert/update a single record using a MERGE statement with Spring JDBC

I have an update/insert SQL query that I created using a MERGE statement. 我有一个使用MERGE语句创建的更新/插入SQL查询。 Using either JdbcTemplate or NamedParameterJdbcTemplate, does Spring provide a method that I can use to update a single record , as opposed to a Batch Update? 使用JdbcTemplate或NamedParameterJdbcTemplate,Spring是否提供一种可以用来更新单个记录而不是批处理更新的方法?

Since this query will be used to persist data from a queue via a JMS listener, I'm only dequeuing one record at a time, and don't have need for the overhead of a batch update. 由于此查询将用于通过JMS侦听器保留来自队列的数据,因此我一次仅使一个记录出队,而无需进行批处理更新。

If a batch is the only way to do it through Spring JDBC, that's fine... I just want to make certain I'm not missing something simpler. 如果批处理是通过Spring JDBC进行处理的唯一方法,那很好。。。我只是想确保自己没有简单的东西。

You can use a SQL MERGE statment using only a one row query containing your parameters. 您只能使用包含参数的单行查询来使用SQL MERGE语句。

For example if you have a table COMPANY containg ID as a key and NAME as an attribute, the MERGE statement would be: 例如,如果您有一个表COMPANY包含ID作为键,而NAME作为属性,则MERGE语句将为:

merge into company c
using (select ? id, ? name from dual) d
on (c.id = d.id)
when matched then update 
   set c.name = d.name
when not matched then insert (c.id, c.name)
   values(d.id, d.name)

If your target table contains the parametrised key, the name will be updated, otherwise a new record will be inserted. 如果目标表包含参数化的键,则name将被更新,否则将插入新记录。

With JDBCTemplate you use the update method to call the MERGE statement, as illustrated below (using Groovy script) 通过JDBCTemplate,您可以使用update方法来调用MERGE语句,如下所示(使用Groovy脚本)

def id = 1
def name = 'NewName'

String mergeStmt = """merge into company c
using (select ? id, ? name from dual) d
on (c.id = d.id)
when matched then update 
   set c.name = d.name
when not matched then insert (c.id, c.name)
   values(d.id, d.name)""";

def updCnt = jdbcTemplate.update(mergeStmt, id, name);

println "merging ${id}, name ${name}, merged rows ${updCnt}" 

Just use one of update methods, for example this one: JdbcTemplate#update instead of BatchUpdate. 只需使用一种update方法,例如以下一种: JdbcTemplate#update而不是BatchUpdate。
Update updates a single record, batchUpdate updates multiple records using JDBC batch Update更新单个记录, batchUpdate使用JDBC批处理更新多个记录

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM