There are two entities:
@Entity class A {
@ManyToMany List<B> bs;
}
@Entity class B {}
I now want to duplicate (clone) an instance of class A
. Is there any way with Hibernate to make a shallow copy of the persistent collection bs
without having to completely initialize all Bs?
In SQL it would be quite easy because you would just have to copy the entries in the association table e.g. by insert into ... select
.
Is there a way to do that without losing the mapping (ie. without native SQL queries) directly with Hibernate?
My almost working solution is to write a query to get all the ids of the Bs and then create Hibernate proxies which I then put into the new Collection. While this is a bit hacky it works quite well, but: the query to get the Ids from the associated elements, always joins table b, which is the thing I would really like to avoid:
HQL: "select b.id from A a join a.bs b where a.id = :id"
generates an SQL like this:
SQL: "select b.id from a join a_b on ... join b on ... where ..."
Since I'm directly selecting the foreign key of a_b the join to b wouldn't be necessary.