简体   繁体   中英

identifier of an instance of ManagerEntity was altered

As per my requirement, I have created ManyToOne relationship using JPA between Customer and Manager

class CustomerEntity{

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

}

class ManagerEntity{

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

 }

Now, I am trying to update/reassign Manager to Customer using below code

public void updateManager(Customer customer) throws Exception {
    CustomerEntity customerEntity = customerDao.find(customer.getId());
    ManagerEntity managerEntity = userDao.find(customer.getManagerId()); 
    customerEntity.setManager(managerEntity);
    getSession().update(entity);
}

But while saving I am getting exception mentioned below

Caused by: org.hibernate.HibernateException: identifier of an instance of ManagerEntity was altered from 10 to 15

As per exception, I can understand that it's trying to update row in ManagerEntity ie child table but I do not want any update in ManagerEntity, Only any existing ManagerEntity should be reassigned to CustomerEntity.

I tried to provide CascadeType.MERGE or CascadeType.DETACH in CustomerEntity but it did not work.

Can anyone suggest me correct way to update CustomerEntity entity ie Parent without updating ManagerEntity ie Child Entity

I would suggest you to do a save update cascade

  1. Associate your child as save-update cascade

  2. Fetch the parent

  3. Update the child entity

  4. Do a saveOrUpdate

Ref : - http://javaforloop.com/hibernate/hibernate-cascade-inverse-example-none-save-update-delete-delete-orphan/

I would suggest you to pass the id of manager to be updated as a separate argument

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

I made a little test and got the same exception with this code:

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

instead of the right one:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM