简体   繁体   English

Hibernate外键是主键

[英]Hibernate foreign key is primary key

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. 因此,您可以看到一个INVQUID_REQUEST_DETAILS有一个请求。 For some reason which I do not understand, I have heard that Hibernate maps this as a many-to-one relationship. 由于某些我不理解的原因,我听说Hibernate将此映射为多对一关系。 I have the following code for my .hbm.xml file: 我的.hbm.xml文件有以下代码:

<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. 请不要让我参考“阅读hibernate文档”,除非你也提供一些解释,它包含非常稀疏的概念解释,我已经阅读过了。 The problem I am having is that my mapping file is obviously wrong since I can't insert any records into my table. 我遇到的问题是我的映射文件显然是错误的,因为我无法在我的表中插入任何记录。

Questions: 问题:

  1. How can I fix my .hbm.xml file? 如何修复.hbm.xml文件? Why? 为什么?
  2. 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? 如果我的外键不是主键,会有什么改变吗?

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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM