Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to copy record using Hibernate (in Java)?

Tags:

java

hibernate

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);
like image 391
marioosh Avatar asked Nov 17 '10 07:11

marioosh


2 Answers

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.

like image 159
Bozho Avatar answered Sep 30 '22 03:09

Bozho


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);
like image 20
cherouvim Avatar answered Sep 30 '22 02:09

cherouvim