我有两个数据表类别和图标。类别表有一个列iconId它是来自图标表的外键。现在我想将数据插入类别表并更新图标表标志列如何在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;
}
答案 0 :(得分:1)
为什么不将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;
}
}