开发者

cloning a existing object with a new primary key

I have 2 objects as follows

class A{
 Set<B>  bs ;

}

class B{
 A a;

}

Now, I want to find A with id as 1 and insert a new record with id as 2 ,all other values will be same. Also Bs associated with A should be newly inserted.

For example, if initial A with id 1, and which is associated with 5 Bs , then after my cod开发者_高级运维e executes, I want 2 As with id=1 and 2 and 10 Bs (5 for A1 and 5 for A2).

I tried following:

    stat tx
    A a= Find A with id a 
    make a transient 
    a.setId(null) ;  As id is auto incremnt
    persist A
    commit tx

Am getting exception as

Found two representations of same collection B.

I think it is because Bs fected has same old id of A while inserting

Note: I'm using HBM files and not JPA.


This is correct it happens because you can't have 2 duplicate objects in the same session.

Please you should detach the object and save it,otherwize please use merge.

You can read more abot merge here:

http://www.hibernate-training-guide.com/merge.html


Assuming none of the Bs' properties need any uniqueness, you should detach all the B objects (perhaps those will get detached too, when you detach A) and change the value of A under each of B object -- assign the detached A.


I would use BeanUtils.copyProperties(..) to duplicate the entity. Then set the ID to null, of course.


Here is my take on this.

  1. The identity of an object in JVM is not the same as its identity in Database. Check this link..
  2. Even though you changed the primary key, the object reference is still the same. So the Session cache cannot have a reference of an object which it already have (Even though you have changed its id).
  3. You will have to create a new object (transient) object to achieve what you are trying to do OR don't let Hibernate manage your identity. Do it yourself. Check the earlier link mentioned.

Also check out this link of transitive persistence. This might help you out.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜