问题
i have a record of data
entity is given as follows in primary key
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Id
@Column(name = "id",unique = true,nullable = false)
public Long id;
what i have tried and even tried with object mapper which has some other issues
Record abc =dao.findById(11);
abc.setId(Null); //not working
dao.save(abc) //not working
so what i am trying to do is a record with primary key as 1 when saved it should save as a new record ?
回答1:
you should create a new object:
Record abc =dao.findById(11);
Record def = new Record(abc);
dao.save(def)
and in Record class, you should have a constructor like this:
public Record(){}
public Record(Record rec){
this.field1 = rec.field1;
}
回答2:
You can do it by creating another Object. Clone object by using beanUtils...
Try with this:
Record abc =dao.findById(11);
Record copyAbc = new Record();
org.springframework.beans.BeanUtils.copyProperties(copyAbc,abc);
copyAbc.setId(null);
dao.save(copyAbc);
回答3:
You can do like this
- Detach your entity from EntityManager
- Set id to null
- Save entity
@PersistenceContext
EntityManager em;
...
em.detach(entity)
EDIT : It appear my answer has some issues. Please don't use it, i finally used the accepted answer
来源:https://stackoverflow.com/questions/61478262/spring-boot-create-a-duplication-of-record-from-mysql