Well I am an "ex" PHP guy, so ofcourse the most straightforward way should be the correct way - shouldn't it! Lets see. Our application uses Hibernate with POJO-s and manages all the data on object level. And I don't want to designate all the fields of a row (=properties of the object) one by one when copying. So I should just:
1. query the object form DB
2. give the object a new identity (reset the ID-s of that object with new ones and/or clone the object ) .
3. modify the new object according to our requirements (assign new relations, set some relations null, ...)
4. insert the object back to DB
Should be easy ... well not quite.
Hibernate keeps track of my POJO-s in a draconian CIA way, not a straightforward PHP way :). When I nullify the ID-s Hibernate just changes the existing object and since it is the same object the DB will be UPDATE when executing em.merge() or em.persist() . So I relly needed to eather clone the object using the "cloneable" interface or detach the object and modify the detached object. I could detach the object by serializing it or closing the EntityManager session but both methods are a bit too cumbersome to me for this simple task. I just need a simple way to copy database rows, something like this:
Object new_obj=copy(old_obj); em.persist(new_obj); .
So here comes the Hibernate3BeanReplicator .It does all the dirty work and still leaves me in control of the copying process. Like this:
Hibernate3BeanReplicator r = new Hibernate3BeanReplicator(null, null, null);
Object o_obj_new = r.copy(o_obj);
o_obj_new.setSomeRelation(null);
o_obj_new.setSomeIntField(0);
o_obj_new.setID(null); // we need to nullify the ID so that Hibernate will treat the result as a new object not a detached instance of an existin object
em.persist(o_obj_new);
No comments:
Post a Comment