Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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?

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.

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.

like image 670
Michael M Avatar asked Sep 02 '25 04:09

Michael M


1 Answers

You can use a SQL MERGE statment using only a one row query containing your parameters.

For example if you have a table COMPANYcontaing IDas a key and NAMEas an attribute, the MERGE statement would be:

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.

With JDBCTemplate you use the update method to call the MERGEstatement, as illustrated below (using Groovy script)

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}" 
like image 156
Marmite Bomber Avatar answered Sep 04 '25 20:09

Marmite Bomber