Hibernate version: 3.2.0
I have a common pattern here.
I have a Person table which contains a person's details. Name, etc.
Contact table which lists a person's phone number, email address etc.
A person may have multiple contactable personas, so the Contact has a foreign key (ManyToOne) link to the Person table.
So, I want a ContactPerson entity which joins these.
in SQL, I'd just do
Code:
select c.*, p.* from Contact c
inner join Person p on p.id=c.person_id
Now you cannot do this in hibernate using annotations (which we use), or .hbm.xml mappings (which we do not
usually use).
But it surely must be possible if you manipulate the mapping metadata before you create the SessionFactory.
I have
Code:
@Table(name="ContactDetails")
@SecondaryTable(name="Person")
public class ContactPerson extends ComponentEntity implements Serializable
{
...
But if I use a .hbm.xml mapping file like this:
Code:
...
<class name="com.aspicio.entity.base.ContactPerson" table="ContactDetails">
<id column="id" type="long"/>
<property name="jobTitle"/>
<property name="phoneNo"/>
<property name="phoneExt"/>
<property name="faxNo"/>
<property name="mobileNo"/>
<property name="emailBox"/>
<property name="emailDomain"/>
<property name="altEmailBox"/>
<property name="altEmailDomain"/>
<many-to-one name="person" class="com.aspicio.entity.base.Person"/>
<many-to-one name="player" class="com.aspicio.entity.base.Player"/>
<set name="generalAnalysis" table="contactdetails_generalanalysis">
<key column="contactdetails_id"/>
<many-to-many column="generalanalysis_id" class="com.aspicio.entity.base.GeneralAnalysis"/>
</set>
<join inverse="true" table="Person">
<key column="id" foreign-key="person_id"/>
<property name="knownAs" column="knownAs"/>
</join>
</class>
...
then I do
Code:
myEjb3Configuration.getClassMapping("com.aspicio.entity.base.ContactPerson");
Then I can see the Join in the Eclipse debugger.
But when it generates the SQL, it generates
Code:
from contact contactper0
left outer join person contactper0_1_ on contactper0_.id=contactper0_1_.id
If, using Eclipse, I poke around in
Code:
myPersistenClass.joins.elementData[0].key.wrappedValue.columns.elementData[0].name
I change the value of name from "id" to "person_id"
It
WORKS! WOOHOO It uses
Code:
from contact contactper0
left outer join person contactper0_1_ on contactper0_.person_id=contactper0_1_.id
My question is. How can I programmatically create that join? Or change the "key" property of the join? I've tried creating a new DependantValue and duplicating all the properties that I can using the available setters, but it won't use
"person_id" as the foreign key on the driving table.
Please help. This has got to be a very common requirement. To join up normalized data into one object! I found several people asking about this. eg:
http://forum.hibernate.org/viewtopic.php?p=2356221