Spring boot create a duplication of record from mysql

人盡茶涼 提交于 2020-05-13 19:26:31

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!