marioosh
marioosh

Reputation: 28556

How to copy record using Hibernate (in Java)?

What is the best way to copy record in the same table ?

Something like that:

Address address = AddressDAO.get(id);
address.setId(null);
AddressDAO.add(address);

Upvotes: 6

Views: 8963

Answers (5)

rahul maindargi
rahul maindargi

Reputation: 5625

Use on cascade Evict for that object in hibernate.

then

Address address = AddressDAO.get(id);
 AddressDAO.evict(address); //Internally session.evict(address);
address.setId(null); // If id is autogenerated
AddressDAO.add(address);

Upvotes: 2

Sumedh
Sumedh

Reputation: 435

This won't make a deep copy...so your copy will refer to children objects of original objects.

Upvotes: 0

waxwing
waxwing

Reputation: 18743

I suggest that you try it. If adress is still persistent (Session-bound) I would assume that there will be problems. You might need a session.evict(address) before setting the id to null.

Upvotes: 1

cherouvim
cherouvim

Reputation: 31903

It would work but it's best if you express your intent (cloning) in your domain mode. Setting a field to null is just an implementation detail and carries no meaning.

Address address = AddressDAO.get(id);
Address clone = address.cloneMe();
AddressDAO.add(clone);

Upvotes: 2

Bozho
Bozho

Reputation: 597106

Yes, that should work.

I'm not sure whether hibernate doesn't check object references, so if this doesn't work you might need to create a new instance and copy all the properties (using BeanUtils.copyProperties, or even BeanUtils.cloneBean(..)), and then set the ID to null/0.

Upvotes: 5

Related Questions