Search code examples
javahibernatespring-web

Cannot pass data from view to controller


Can anyone explain, how to pass id from view to controller? sources

The problem: when trying to edit existing task, I have a new task added. With new edited name.

@RequestMapping("/edit/{id}")
public String editTask(@PathVariable("id") Long id, Model model) {
    model.addAttribute("task", taskService.getTaskById(id));
    model.addAttribute("tasks", taskService.listTasks());

    return "tasks";
}

@RequestMapping(value = "/add", method = RequestMethod.POST)
public String addTask(@ModelAttribute("task") Task task) {
    if (task.getId() == null) {
        taskService.addTask(task);
    } else {
        taskService.updateTask(task);
    }
    return "redirect:/";
}

So, in addTask() task.id always = null, but task.taskName is not null. What's wrong with Long id? Maybe, this affects somehow?

@Transactional
@Entity(name = "tasks")
public class Task {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Basic
    private String taskName;

Solution

  • Problem was solved, when I add "=0" to my id declaration:

    @Entity(name = "tasks")
    public class Task {
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        private Long id = 0L;