如何使用 spring jdbc 模板将一个查询插入数据 table 并更新另一个 table
How to write one query insert data to table and update another one table using spring jdbc template
我有两个数据 table 类别和图标。类别 table 有一个单列 iconId 它是来自图标 table.Now 的外键 我想将数据插入类别 table 并更新图标 table 标志列 如何在 sping 中执行此操作jdbc 模板
private final String addCategorySql ="INSERT INTO CATEGORY(TYPE,ICONID)"
+" VALUES(?,?) UPDATE ICON SET FLAG=? WHERE ICONID=? ";
public boolean addNewCategory(Category category){
Object [] parameters = {category.getType(),category.getIconId(),1,category.getIconId()};
try {
int rows = jdbcTemplate.update(addCategorySql, parameters);
if (rows == 1) {
return true;
} else {
return false;
}
} catch (Exception e) {
logger.error("Exception : " , e);
throw e;
}
为什么不将 sql 分成 2 个语句?分类是否插入,图标是否更新,会更清楚,你能理解。
private final String addCategorySql = "INSERT INTO CATEGORY(TYPE,ICONID)"
+ " VALUES(?,?);"
private final String updateIconSql = "UPDATE ICON SET FLAG=1 WHERE ICONID=? ";
public boolean addNewCategory(Category category) {
try {
int updatedRows = 0;
int insertedRows = jdbcTemplate.update(addCategorySql, category.getType(), category.getIconId());
if (insertedRows == 1) { //we are updating Icon table only when any category inserted. Otherwise we return false;
updatedRows = jdbcTemplate.update(updateIconSql, category.getIconId());
if (updatedRows == 1) {
return true;
} else {
return false;
}
} else {
return false;
}
} catch (Exception e) {
logger.error("Exception : ", e);
throw e;
}
}
我有两个数据 table 类别和图标。类别 table 有一个单列 iconId 它是来自图标 table.Now 的外键 我想将数据插入类别 table 并更新图标 table 标志列 如何在 sping 中执行此操作jdbc 模板
private final String addCategorySql ="INSERT INTO CATEGORY(TYPE,ICONID)"
+" VALUES(?,?) UPDATE ICON SET FLAG=? WHERE ICONID=? ";
public boolean addNewCategory(Category category){
Object [] parameters = {category.getType(),category.getIconId(),1,category.getIconId()};
try {
int rows = jdbcTemplate.update(addCategorySql, parameters);
if (rows == 1) {
return true;
} else {
return false;
}
} catch (Exception e) {
logger.error("Exception : " , e);
throw e;
}
为什么不将 sql 分成 2 个语句?分类是否插入,图标是否更新,会更清楚,你能理解。
private final String addCategorySql = "INSERT INTO CATEGORY(TYPE,ICONID)"
+ " VALUES(?,?);"
private final String updateIconSql = "UPDATE ICON SET FLAG=1 WHERE ICONID=? ";
public boolean addNewCategory(Category category) {
try {
int updatedRows = 0;
int insertedRows = jdbcTemplate.update(addCategorySql, category.getType(), category.getIconId());
if (insertedRows == 1) { //we are updating Icon table only when any category inserted. Otherwise we return false;
updatedRows = jdbcTemplate.update(updateIconSql, category.getIconId());
if (updatedRows == 1) {
return true;
} else {
return false;
}
} else {
return false;
}
} catch (Exception e) {
logger.error("Exception : ", e);
throw e;
}
}