使用 spring jdbctemplate 更新一行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11843658/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
update a row using spring jdbctemplate
提问by smya.dsh
I am new to spring. I am developing a CRUD application using spring jdbc template. I am done with insert and select. but in update am facing some problem. can anybody provide me a simple example of update and delete using jdbctemplate. thnks in advance.
我是春天的新手。我正在使用 spring jdbc 模板开发 CRUD 应用程序。我完成了插入和选择。但在更新中我面临一些问题。任何人都可以为我提供一个使用 jdbctemplate 进行更新和删除的简单示例。提前谢谢。
MY CONTROLLER-
我的控制器-
@RequestMapping(method = RequestMethod.GET)
public String showUserForm(@ModelAttribute(value="userview") User user,ModelMap model)
{
List list=userService.companylist();
model.addAttribute("list",list);
return "viewCompany";
}
@RequestMapping( method = RequestMethod.POST)
public String add(@ModelAttribute(value="userview") @Valid User user, BindingResult result)
{
userValidator.validate(user, result);
if (result.hasErrors()) {
return "viewCompany";
} else {
userService.updateCompany(user);
System.out.println("value updated");
return "updateSuccess";
}
when i click on update button the edited values should be updated in my DB according to the row ID , my problem is how to map the row id from jsp to controller.
当我点击更新按钮时,编辑的值应该根据行 ID 在我的数据库中更新,我的问题是如何将行 ID 从 jsp 映射到控制器。
回答by JB Nizet
Straight from the documentation:
直接来自文档:
The following example shows a column updated for a certain primary key. In this example, an SQL statement has placeholders for row parameters. The parameter values can be passed in as varargs or alternatively as an array of objects. Thus primitives should be wrapped in the primitive wrapper classes explicitly or using auto-boxing.
以下示例显示为某个主键更新的列。在此示例中,SQL 语句具有用于行参数的占位符。参数值可以作为可变参数传入,也可以作为对象数组传入。因此,原语应该显式地包装在原语包装类中或使用自动装箱。
import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcTemplate;
public class ExecuteAnUpdate {
private JdbcTemplate jdbcTemplate;
public void setDataSource(DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
public void setName(int id, String name) {
this.jdbcTemplate.update(
"update mytable set name = ? where id = ?",
name, id);
}
}
回答by sonam
You can simply use request.getParamater()or command objectto pass values from jsp to controller.
您可以简单地使用request.getParamater()或command object将值从jsp 传递到控制器。

