Spring JDBC Template Conditional Insert
I am trying to write a conditional batch insert based on Java Parameters, for example
List<Object[]> params = new ArrayList();
params.add(new Object[]{1, 2, 3});
getSimpleJdbcTemplate.batchUpdate(
"INSERT INTO SomeTable( colA, colB, colC)" +
" VALUES(?开发者_开发百科, ?, ?)" +
" WHERE EXISTS ( // some condition )", params);
This obviously does not work, and the closest example I have found involves selecting the INSERT values from tables, instead of the List arguments, which is what I need. How can I reference the Object[] parameters as part of the INSERT values?
Thank you.
I'd say that you should move this condition in a separate SELECT.
As your example, you should try following syntax and the SimpleJdbcOperations.update method:
getSimpleJdbcTemplate.update(
" INSERT INTO SomeTable( colA, colB, colC)" +
" SELECT srcA, srcB, srcC" +
" FROM src_table" +
" WHERE EXISTS ( // some condition )",
params
);
Additionally, I've been using StringTemplate for generation of dynamic SQL. It's the best language I ever use.
for Example(As StringTemplate Syntax):
StringTemplate tmpl = new StringTemplate(
" SELECT *" +
" FROM some_table" +
" WHERE 1 = 1" +
"$search_age:{ AND age = ?}$" +
"$search_name:{ AND name = ?}$"
);
/**
* if param_age is not null, "AND age = ?" would be included in argumented sql,
* same as param_name
*/
tmpl.setAttribute("age", param_age);
tmpl.setAttribute("name", param_name);
// :~)
String sqlTmpl = tmpl.toString(); // final SQL generated
精彩评论