hibernate - Spring MVC + hibernate : id to load is required for loading

标签 hibernate spring-mvc

这是一个菜鸟问题,我知道,我很抱歉。我正在尝试使用 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 服务/应用程序的问题。

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

如果您在网络、休息或 WS session 中保留属性时遇到困难,可以在此处提供更多详细信息,或提出新问题。

关于hibernate - Spring MVC + hibernate : id to load is required for loading,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21505894/

相关文章:

java - 当实体映射为多对一时,使用 Hibernate 热获取对象列表

java - Hibernate 找不到属性的 setter (org.hibernate.PropertyNotFoundException)

用于 XSS 保护的请求正文中的 Spring Boot 转义字符

java - 运行 spring mvc 项目时出现一些错误

java - 为什么 org.springframework.beans.factory.BeanCreationException :?

java - @Transactional 继续异常处理

java - 当嵌套方法中发生错误时,不会发生事务回滚

java - 使用 HQL(Hibernate 查询语言)转换查询 Oracle

mysql - Grails 中属性的自引用关系?

java - Ajax调用数据不绑定(bind)