Hibernate foreign key is primary key

hibernate, java

Solution

Not sure where you got your information from, but you can certainly model this as a one-to-one. Here's an example of how.

<hibernate-mapping>
  <class name="InvalidRequestDetails" table="INVALID_REQUEST_DETAILS">  
  <id name="id" column="fk_req_id">
    <generator class="foreign">
        <param name="property">request</param>
    </generator>
  </id>

  ... (other column mappings omitted) ...    

  <one-to-one name="request" class="Request" constrained="true" />
 </class>
</hibernate-mapping>

Problem

``` DB Table REQUEST: { primary key REQUEST_ID, String REQUEST_DETAILS } DB Table INVALID_REQUEST_DETAILS{ (foreign key, primary key) fk_req_id references REQUEST.REQUEST_ID, String INVALID_COMMENTS, String APPROVER_NAME } ``` So as you can see there is one REQUEST to one INVALID_REQUEST_DETAILS. For some reason which I do not understand, I have heard that Hibernate maps this as a many-to-one relationship. I have the following code for my .hbm.xml file: ``` <hibernate-mapping> <class name="InvalidRequestDetails" table="INVALID_REQUEST_DETAILS"> <id name="id" column="fk_req_id"> <generator class="foreign"> <param name="property">request</param> </generator> </id> ... (other column mappings omitted) ... <many-to-one name="request" class="Request" unique="true" not-null="true" /> </class> </hibernate-mapping> ``` Please don't refer me to "read the hibernate documentation" unless you also provide some explanation, it contains very sparse explanations of concepts and I have already read it. The problem I am having is that my mapping file is obviously wrong since I can't insert any records into my table. Questions: - How can I fix my .hbm.xml file? Why? - If I have a logically one-to-one relationship as I explained above, why do I need a many-to-one tag? What's really the difference between many-to-one and one-to-one here? When do you use which? Would anything change if my foreign key was NOT also a primary key?

Original source