How to clone a JPA entity

Viewed 63459

I have a JPA entity already persisted in the database.
I would like to have a copy of it (with a different id), with some fields modified.

What is the easiest way to do this? Like:

  • setting it's @Id field to null and persisting it will work?
  • will I have to create a clone method for the entity (copying all fields except the @Id)?
  • is there any other approach (like using a cloning framework)?
8 Answers

You are better off using a copy constructor and controlling exactly what attributes need to be cloned.

So, if you have a Post entity like this one:

@Entity(name = "Post")
@Table(name = "post")
public class Post {
 
    @Id
    @GeneratedValue
    private Long id;
 
    private String title;
 
    @OneToMany(
        mappedBy = "post",
        cascade = CascadeType.ALL, 
        orphanRemoval = true
    )
    private List<PostComment> comments = new ArrayList<>();
 
    @OneToOne(
        mappedBy = "post",
        cascade = CascadeType.ALL, 
        orphanRemoval = true, 
        fetch = FetchType.LAZY
    )
    private PostDetails details;
 
    @ManyToMany
    @JoinTable(
        name = "post_tag",
        joinColumns = @JoinColumn(
            name = "post_id"
        ),
        inverseJoinColumns = @JoinColumn(
            name = "tag_id"
        )
    )
    private Set<Tag> tags = new HashSet<>();
 
    //Getters and setters omitted for brevity
 
    public void addComment(
            PostComment comment) {
        comments.add(comment);
        comment.setPost(this);
    }
 
    public void addDetails(
            PostDetails details) {
        this.details = details;
        details.setPost(this);
    }
 
    public void removeDetails() {
        this.details.setPost(null);
        this.details = null;
    }
}

It does not make sense to clone the comments when duplicating a Post and using it as a template for a new one:

Post post = entityManager.createQuery(
    "select p " +
    "from Post p " +
    "join fetch p.details " +
    "join fetch p.tags " +
    "where p.title = :title", Post.class)
.setParameter(
    "title", 
    "High-Performance Java Persistence, 1st edition"
)
.getSingleResult();
 
Post postClone = new Post(post);
postClone.setTitle(
    postClone.getTitle().replace("1st", "2nd")
);
entityManager.persist(postClone);

What you need to add to the Post entity is a copy constructor:

/**
 * Needed by Hibernate when hydrating the entity 
 * from the JDBC ResultSet
 */
private Post() {}
 
public Post(Post post) {
    this.title = post.title;
 
    addDetails(
        new PostDetails(post.details)
    );
 
    tags.addAll(post.getTags());
}

This is the best way to address the entity clone/duplication problem. Any other methods, which try to make this process completely automatic, miss the point that not all attributes are worth duplicating.

I just tried setting the id to null and it worked

address.setId(null);
address = addrRepo.save(address);

setting the id to null made it so it saved into a new record with new id since i have it automatically generated.

ModelMapper lib can be used for this purpose.

public MyEntity clone(MyEntity myInstance) {
    MyEntity newInstance = new MyEntity();
    new ModelMapper().map(myInstance, newInstance);
    return newInstance;
}

just add the maven dependency

<dependency>
    <groupId>org.modelmapper</groupId>
    <artifactId>modelmapper</artifactId>
    <version>2.3.2</version>
</dependency>
Related