Hibernate: How to fix "identifier of an instance altered from X to Y"?

Are you changing the primary key value of a User object somewhere? You shouldn't do that. Check that your mapping for the primary key is correct.

What does your mapping XML file or mapping annotations look like?


You must detach your entity from session before modifying its ID fields


In my case getters and setter names were different from Variable name.

private Long stockId;
    public Long getStockID() {
        return stockId;
    }
    public void setStockID(Long stockID) {
        this.stockId = stockID;
    }

where it should be

public Long getStockId() {
    return stockId;
}
public void setStockId(Long stockID) {
    this.stockId = stockID;
}

In my case, the PK Field in hbm.xml was of type "integer" but in bean code it was long.