Spring MVC + Hibernate:要加载的ID需要加载


问题内容

我知道这是一个菜鸟问题,对不起。我正在尝试使用Hibernates session.merge()方法编辑现有记录,但出现以下错误:

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

这是我的对象:

@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

这是服务层方法:

 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);
 }

这是控制器的POST方法:

@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";
    }
}

我想念什么?任何帮助都感激不尽。


问题答案:

问题不在于hibernate。 title.getTitleId()将其传递给时为null session.get(),这是Web服务/应用程序的问题。

  1. 您的GET可能未在模型对象中提供ID
  2. 您的客户端代码(表单,客户端应用程序,ajax调用等)可能未保留GET和POST之间的ID。
  3. 您的POST可能未在模型对象中提供ID。

如果您难以在整个Web,REST或WS会话中保留属性,则可以在此处提供更多详细信息,或者提出一个新问题。