There's a standard Merge (SQL) statement. But not all RDBMS's support it. Some of them have alternatives.
JDBCTemplate : either Update or Insert if ID doesn't exist
-
06-10-2022 - |
سؤال
Please see below the method which i used for updating a field in the table,
and now i have a condition if Id exists in the table then update the relative field otherwise insert a new record in the table.
Update if id exists
Insert a new record if id doesn't exist in table
Is there any way to do so via batch update which fulfils both condition or any other way as i have to deal with hundreds of row altogether.
public void updateTable(List<TestClass> testList){
String UPDATE_ITEM_ARTICLENO = "UPDATE itemTable SET articleno=? WHERE itemId=?";
jdbcTemplate.batchUpdate(UPDATE_ITEM_ARTICLENO, new BatchPreparedStatementSetter() {
@Override
public void setValues(PreparedStatement ps, int i) throws SQLException {
TestClass article = testList.get(i);
ps.setString(1, article.getItemId());
ps.setString(2, article.getArticleno());
}
@Override
public int getBatchSize() {
return testList.size();
}
});
}
المحلول
لا تنتمي إلى StackOverflow