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 B
s associated with A
should be newly inserted.
For example, if initial A
with id 1
, and which is associated with 5 B
s , then after my cod开发者_高级运维e executes, I want 2 A
s with id=1 and 2 and 10 B
s (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 B
s 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 B
s' 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.
- The identity of an object in JVM is not the same as its identity in Database. Check this link..
- 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).
- 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.
精彩评论