Java ManagerEntity实例的标识符已更改

Java ManagerEntity实例的标识符已更改,java,hibernate,many-to-one,Java,Hibernate,Many To One,根据我的要求,我已经使用JPA在客户和经理之间建立了多通关系 class CustomerEntity{ @ManyToOne @JoinColumn(name = "manager_id", referencedColumnName = "id") private ManagerEntity manager; } class ManagerEntity{ @OneToMany(mappedBy = "manager", fetch = Fetch

根据我的要求,我已经使用JPA在客户和经理之间建立了多通关系

class CustomerEntity{

    @ManyToOne
    @JoinColumn(name = "manager_id", referencedColumnName = "id")
    private ManagerEntity manager;

}

class ManagerEntity{

        @OneToMany(mappedBy = "manager", fetch = FetchType.LAZY)
        private List<CustomerEntity> customerlist;

 }
但在保存时,我遇到了下面提到的异常

原因:org.hibernate.HibernateException:ManagerEntity实例的标识符从10更改为15

根据例外情况,我可以理解它正在尝试更新ManagerEntity中的行,即子表,但我不希望在ManagerEntity中进行任何更新,只应将任何现有ManagerEntity重新分配给CustomerEntity

我试图在CustomerEntity中提供CascadeType.MERGE或CascadeType.DETACH,但没有成功


是否有人可以建议我更新CustomerEntity实体(即父实体)而不更新ManagerEntity(即子实体)的正确方法我建议您执行保存更新级联

  • 将您的孩子关联为“保存更新级联”

  • 取回父对象

  • 更新子实体

  • 执行saveOrUpdate

  • 参考:-

    我建议您将要更新的经理id作为单独的参数传递

    public void updateManager(Customer customer , Long managerId) throws Exception {
    
    //Below code will fetch the customer you need to update
        CustomerEntity customerEntity = customerDao.find(customer.getId());
        ManagerEntity managerEntity = new ManagerEntity();
        managerEntity.setId(managerId);
        customerEntity.setManager(managerEntity);
        getSession().saveOrUpdate(customerEntity);
    }
    

    我做了一个小测试,得到了与此代码相同的异常:

    void setManager(ManagerEntity managerEntity) {
        this.manager.setId(managerEntity.getId());
    }
    
    而不是正确的一个:

    void setManager(ManagerEntity managerEntity) {
        this.manager = managerEntity;
    }
    

    为什么不执行customerEntity.getManager().setName(“新名称”)呢?您的客户应该拥有该管理器,这样您就不必从数据库中检索。在我看来,您正在更新的manager实体与客户的实体不同,hibernate抱怨为什么要单独获取ManagerEntity?当您获取CustomerEntity时,它也应该获取Manager。因此,无需在客户实体中设置经理。将fetch type更改为eager,然后查看代码获取管理器是否与客户一起使用。除非您在.setManager方法中执行了一些奇怪的操作,否则它看起来是正确的。能否显示代码?我尝试使用getSession()退出managerEntity。退出(managerEntity);它保存了客户性,但不保存管理性,这是显而易见的。你们能建议保存经理实体的方法吗?我不确定你们想更新客户而不是经理。如果你想更新子实体,你需要级联它。很抱歉Saket。我打错了问题。我根本不想保存管理性。你能不能建议在更新父项时不要更新子项,我不想更新子项实体。再次为我上面的错误评论感到抱歉。那么你想用什么信息更新客户?你能详细说明一下吗?Saket你明白了。这是客户编辑功能,默认情况下,客户有一些信息,如姓名或任何其他个人信息,也有默认的经理分配给它,而现在编辑任何现有的经理可以分配给客户。正如我在问题中提到的,CustomerEntity(在我的数据库中代表customer_tbl)具有ManagerEntity(在我的数据库中代表manager_tbl),它在customer_tbl中创建了外键manager_id。我需要更新我的客户tbl中的经理id列。请参考问题中提到的关系结构。希望,我能正确地澄清。
    void setManager(ManagerEntity managerEntity) {
        this.manager = managerEntity;
    }