【问题标题】:Update table using Hibernate使用 Hibernate 更新表
【发布时间】:2018-05-03 07:00:30
【问题描述】:

我正在一个项目下工作,该项目使用 Hibernate 更新 MySQL 表中的数据。每当我运行项目时,异常如下所示。

[批量更新从更新[0]返回意外的行数;实际的 行数:0;预计:1]

控制器

@RequestMapping(value = "/disableEmployeeMaster", method = RequestMethod.POST)
public @ResponseBody void disableEmployee(HttpServletRequest request)
{
    EmployeeMaster employeeMaster = new EmployeeMaster();
    try
    {
        String employeeId = request.getParameter("employeeId");
        employeeMaster.setIsDel("Y");
        mainService.disableEmployee(employeeId , employeeMaster);
    }
    catch(Exception e)
    {
        logger.error(e.getMessage());
    }
}

服务实施

@Override
public void disableEmployee(String Id, EmployeeMaster employeeMaster) {
    Session session = null;
    Transaction transaction = null;
    try
    {
        session = sessionFactory.openSession();
        transaction = session.beginTransaction();
        session.update(Id, employeeMaster);
        transaction.commit();
    }
    catch(Exception e)
    {
        System.out.println(e.getMessage());
    }
    finally
    {
        session.close();
    }
}

【问题讨论】:

  • session.update() 方法参数是模型的对象。如果你有PK,它会自动更新行。
  • 根据规范void update(String entityName, Object object),我想Id "E02" 不应该是entityName。你能告诉我们你的EmployeeMaster实体类吗?
  • "E02" 不是实体,它是员工 ID。 “employeeMaster”是实体。
  • 您在EmployeeMaster 中的主要内容是什么?有@Id 字段的那个?

标签: java mysql hibernate


【解决方案1】:

您尚未将employeeId 设置为EmployeeMaster 类对象。 更新任何实体都需要它的主键。 您可以参考以下代码:

employeeMaster.setEmployeeId(employeeId);

控制器

@RequestMapping(value = "/disableEmployeeMaster", method = RequestMethod.POST)
public @ResponseBody void disableEmployee(HttpServletRequest request)
{
    EmployeeMaster employeeMaster = new EmployeeMaster();
    try
    {
        String employeeId = request.getParameter("employeeId");
        employeeMaster.setEmployeeId(employeeId);
        employeeMaster.setIsDel("Y");
        mainService.disableEmployee(employeeId , employeeMaster);
    }
    catch(Exception e)
    {
        logger.error(e.getMessage());
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-03
    相关资源
    最近更新 更多