这是一个菜鸟问题,我知道,我很抱歉。我正在尝试使用 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);
}
这是 Controller 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()
传递给 session.get()
时,它为 null,这是您的 Web 服务/应用程序的问题。
- 您的 GET 可能未在模型对象中提供 ID
- 您的客户端代码(表单、客户端应用程序、ajax 调用,无论是什么)可能不会保留 GET 和 POST 之间的 ID
- 您的 POST 可能未在模型对象中提供 ID。
如果您在网络、休息或 WS session 中保留属性时遇到困难,可以在此处提供更多详细信息,或提出新问题。
关于hibernate - Spring MVC + hibernate : id to load is required for loading,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21505894/