Pilly
Pilly

Reputation: 29

Java Spring, how to retrieve a record and post a duplicate with new unique key?

I want to retrieve an existing record and persist a duplicate of it using a new ID. When I try this I get an error that states: "identifier of an instance ..... was altered from 1 to null"

This is kind of like a general summary of how i coded it. I set the newEntity ID to null thinking that my sequence generator will auto generate a ID.

Entity newEntity = repo.findById(id);
Entity newEntity.setId(null);
repo.save(newEntity);

Upvotes: 2

Views: 1621

Answers (2)

Alien
Alien

Reputation: 15898

Your current way is not working because entity is still attached with the session so whatever update you make for this entity will be persisted in this entity itself. You can use copyProperties method of BeanUtils class like below so that the new entity will be fresh detached entity.

org.springframework.beans.BeanUtils.copyProperties(Object source, Object target)

Entity existingEntity = repo.findById(id);
Entity newEntity = new Entity();
BeanUtils.copyProperties(existingEntity,newEntity);
newEntity.setId(null);
repo.save(newEntity);

Upvotes: 3

Sridhar Patnaik
Sridhar Patnaik

Reputation: 1118

You cannot directly set id to null. Try deep cloning of entity and then save it. you can refer to https://www.baeldung.com/java-deep-copy for further info

Upvotes: 0

Related Questions