Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

update a row using spring jdbctemplate

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.

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.

like image 474
smya.dsh Avatar asked Aug 07 '12 10:08

smya.dsh


2 Answers

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.

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);
    }
}
like image 134
JB Nizet Avatar answered Nov 14 '22 12:11

JB Nizet


You can simply use request.getParamater() or command object to pass values from jsp to controller.

like image 1
sonam Avatar answered Nov 14 '22 12:11

sonam