Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring MVC + Hibernate: id to load is required for loading

This is such a noob question, I know and I apologize. I'm trying to edit existing record with Hibernates session.merge() method and I get the following error:

java.lang.IllegalArgumentException: id to load is required for loading

This is my object:

@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "TITLE_ID", unique = true, nullable = false)
private Integer titleId;

@NotNull
@NotBlank
@Column(name = "TITLE_DESCRIPTION", nullable = false, length = 10)
private String titleDescription;
// default constructor, getters & setters

This is service layer method:

 public void edit(Title title) {
     logger.debug("Editing existing title");

     // Retrieve session from Hibernate
     Session session = sessionFactory.getCurrentSession();

     // Retrieve existing title via id
     Title existingTitle = (Title) session.get(Title.class, title.getTitleId());

     // Assign updated values to this title
     existingTitle.setTitleDescription(title.getTitleDescription());

     // Save updates
     session.merge(existingTitle);
 }

This is controller POST method:

@RequestMapping(value="/edit", method = RequestMethod.POST)
public String postEditTitle(@Valid @ModelAttribute("titleAttribute") Title title,
                        BindingResult result) {

    logger.debug("Received request to edit title");

    if (result.hasErrors()) {
        return "editTitle";
    }
    else {
        titleService.edit(title);
        return "redirect:/essays/main/title";
    }
}

What am I missing? Any help will be much appreciated.

like image 836
just_a_girl Avatar asked Feb 02 '14 01:02

just_a_girl


1 Answers

The problem isn't with Hibernate. title.getTitleId() is null when you pass it to session.get(), and that's a problem with your web service/application.

  1. Your GET might not be providing the id in the model object
  2. Your client code (form, client app, ajax call, whatever it is) might not be retaining the ID between the GET and POST
  3. Your POST might not be providing the id in the model object.

You can provide more details here, or ask a new question, if you're having difficulties retaining attributes across the web, rest or WS session.

like image 102
Paul Hicks Avatar answered Oct 13 '22 21:10

Paul Hicks