问题描述,
有两张表 table_1, table_2
主键 a , b 相同。 用 hibernate tools 生成相应的代码。
调用查询出错, 原因 。 联合主健需要相同的类。
----------------------------------------------------------------------------------
https://issues.jboss.org/browse/HIBERNATE-118
and not if i define the mapping accordingly as:
In Product.hbm.xml
<composite-id name="compProduct" class="CompProduct">
<key-property name="pid" type="string" column="PRODUCTID" length="10"></key-property>
<key-property name="desc" type="string" column="DESC" length="10"></key-property>
</composite-id>
In ProductBasic.hbm.xml
<composite-id name="compProductBasic" class="CompProductBasic">
<key-property name="productId" column="PRODUCTID" type="string" length="10"/>
<key-property name="productDesc" column="DESC1" type="string" length="10"/>
</composite-id>
Now while fetching Product (and internally it will fetch ProductBasic), it gives the following exception:
org.hibernate.TypeMismatchException: Provided id of the wrong type. Expected: class model.CompProductBasic, got class model.CompProduct
So the only approach for one-to-one with composite-id is to have a common compositeId class..
The link http://docs.jboss.org/hibernate/stable/core/reference/en/html_single/#mapping-declaration-compositeid
recommends 3 solutions (3rd being to have a common compositeId class) but as per my understanding 1st and 2nd approach will give exception for one-to-one with composite-id ...
I think this hibenate restriction (of having common CompositeId class for one-to-one relationship) is not good as it puts a constraint on how domain model (java) should be which could not be possible everytime in legacy applications..
NOTE: This is the similar exception if i don't use a seperate class for CompositeId..
Hibernate docs have a statement about this situation as :
Unfortunately, this approach to composite identifiers means that a persistent object is its own identifier. There is no convenient "handle" other than the object itself. You must instantiate an instance of the persistent class itself and populate its identifier properties before you can load() the persistent state associated with a composite key. We call this approach an embedded composite identifier, and discourage it for serious applications.
A second approach is what we call a mapped composite identifier, where the identifier properties named inside the <composite-id> element are duplicated on both the persistent class and a separate identifier class.
<composite-id class="MedicareId" mapped="true">
<key-property name="medicareNumber"/>
<key-property name="dependent"/>
</composite-id>
Useful Links : https://forum.hibernate.org/viewtopic.php?f=1&t=993886