Hi all,
Suppose I have a table
PRODUCT with columns
ID, DESCRIPTION, and TYPE.
My goal is to map a Product class. It has a set "similarProducts" that contains all Products with the same TYPE value as the parent Product. (It is OK if similarProducts also includes the original parent Product.)
I'm trying to avoid creating a separate association table because it seems so unnecessary.
Here are two approaches that come close but ultimately fail:
Code:
VERSION 1.
<set name="similarProducts" >
<key property-ref="type">
<column name="TYPE" />
</key>
. . .
This populates similarProducts correctly. However, if I load 2 products with the same TYPE into the session, I eventually get "no session" exceptions as described in
http://opensource.atlassian.com/projects/hibernate/browse/HHH-2862. Apparently Hibernate forbids having a collection with a non-unique key (product type, in this case) that is shared by multiple parents.
So let's try this...
Code:
VERSION 2.
<set name="similarProducts" >
<key>
<column name="ID"/>
</key>
<one-to-many class="Product" />
<loader query-ref="similarProductsQuery" />
. . .
<sql-query name="similarProductsQuery">
<load-collection alias="product" role="Product.similarProducts"/>
SELECT {product.*}
FROM PRODUCT product
WHERE TYPE IS NOT NULL AND TYPE = (SELECT TYPE FROM PRODUCT WHERE ID = ?)
</sql-query>
This solves the first problem by specifying a unique key for each similarProducts collection, and the query retrieves the right resultset. However, Hibernate's CollectionLoadContext splits the resultset by Product ID, and similarProducts ends up containing only a copy of the original parent Product (since the other products with matching TYPE have IDs that do not match the collection key).
This is where I am stuck. I have tried numerous other workarounds which all lead to exceptions deep within Hibernate.
Any help would be much appreciated!
Thanks in advance,
John VanderWood