0

I have entity User:

@Entity
@Table(name = "users")
public class User{
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;

    @Column(name = "name", nullable = false)
      private String name;

     @OneToMany(fetch = FetchType.LAZY, mappedBy = "parentid", cascade=CascadeType.ALL)
    private List<Lesson> lessonList=new ArrayList<>();
}

and entity Lesson

    @Entity
    @Table(name = "lesson")
    public class Lesson{

        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        private int id;

        @Column(name = "name", nullable = false)
          private String name;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "parentid")
    private User parentid;

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "parentid2", cascade=CascadeType.ALL)
        private List<Exercise> exerciseList=new ArrayList<>();
    }

I need to make a copy(deep copy) of lesson of user1 and add this copy to another user2. In the end I need user1 has lesson and user2 has copy of lesson.

Rémi Bantos
  • 1,899
  • 14
  • 27
Sergei
  • 41
  • 2
  • 11
  • 2
    This has already been answered/discussed [here](http://stackoverflow.com/questions/11625096/cloning-jpa-entity) and [here](http://stackoverflow.com/questions/1106632/deep-copy-in-jpa) – Rémi Bantos Nov 07 '16 at 17:25

1 Answers1

0

Well simplest way of doing it by using XStream api. Annotate your @Id field with @XStreamOmitField annotation, Then write your object to xml like below.

XStream xstream = new XStream(new StaxDriver());
String xml = xstream.toXML(yourObject);

Read it back

YourObject yourObject = (Person)xstream.fromXML(xml);
Dangling Piyush
  • 3,658
  • 8
  • 37
  • 52