You could use the formula attribute on the many-to-one to achieve this. Here is something that works for me.
DocumentRelations has a many-to-one relation with Document class. In the DocumentRelations object, I can set the documentID and be able to retrieve docRelations.getDocument() and get the same document object. My mapping files are
Document.hbm.xml
Code:
<hibernate-mapping package="com.rajasaur.hibernate3.forum935920">
<class name="Document" table="Document">
<id name="id" type="int" unsaved-value="0">
<column name="id" sql-type="int" not-null="true" />
<generator class="increment" />
</id>
<property name="name" />
</class>
</hibernate-mapping>
and DocRelations.hbm.xml is
Code:
<hibernate-mapping package="com.rajasaur.hibernate3.forum935920">
<class name="DocumentRelations" table="DocumentRelations">
<id name="id" type="int" unsaved-value="0">
<column name="id" sql-type="int" not-null="true" />
<generator class="increment" />
</id>
<property name="documentID" column="document_id"/>
<many-to-one class="Document" name="document"
insert="false" update="false">
<formula>
(select d.id from Document d where d.id = document_id)
</formula>
</many-to-one>
</class>
</hibernate-mapping>
Checkout the formula on the many-to-one in the DocumentRElations.hbm.xml. Doing a Testcase like
Code:
Document doc = (Document) s.load(Document.class, new Integer(1));
DocumentRelations docRelations = (DocumentRelations) s.createQuery("from DocumentRelations dr" +
" where dr.documentID = 1").uniqueResult();
System.out.println("Document Name: " + docRelations.getDocument().getName());
assertTrue("Doc Object is the same", doc == docRelations.getDocument());
passes just fine.