hibernate映射文件中的Id和Property元素

时间:2014-09-07 05:59:04

标签: java hibernate

来自Hibernate文档: id元素是identifier属性的声明。 name =“id”mapping属性声明了JavaBean属性的名称,并告诉Hibernate使用getId()和setId()方法来访问该属性。 column属性告诉Hibernate映射表的哪一列保存主键值。

嵌套的生成器元素指定标识符生成策略(也就是如何生成标识符值?)。

我们有,

 <id 

   name="id" column="Id_Column in Database">

   <generator class=""/>

 </id>

为什么不能这样呢?

 <property 

  name="id" column="Id_Column in Database">

  <generator class=""/>

 </property>

这有什么具体原因吗?

2 个答案:

答案 0 :(得分:3)

我认为,唯一的区别可能是表现。因为在第二种情况下,Hibernate引擎(XML Parser)必须获取每个属性标记以识别它是否是主要标记,而在第一种情况下通过具有单独的标记,很容易获取一个标记,并且它也更易读

答案 1 :(得分:0)

让我们使用Hibernate映射文件 DTD(文档类型定义)来比较<id><property>标记的定义:

<id>标记的定义:

<!-- Declares the id type, column and generation algorithm for an entity class.
If a name attribut is given, the id is exposed to the application through the 
named property of the class. If not, the id is only exposed to the application 
via Session.getIdentifier() -->

<!ELEMENT id (meta*,column*,type?,generator?)>
    <!ATTLIST id name CDATA #IMPLIED>
    <!ATTLIST id node CDATA #IMPLIED>
    <!ATTLIST id access CDATA #IMPLIED>
    <!ATTLIST id column CDATA #IMPLIED>
    <!ATTLIST id type CDATA #IMPLIED>
    <!ATTLIST id length CDATA #IMPLIED>
    <!ATTLIST id unsaved-value CDATA #IMPLIED>

<property>标记的定义:

<!-- Property of an entity class or component, component-element, composite-id, etc. 
JavaBeans style properties are mapped to table columns. -->

<!ELEMENT property (meta*,(column|formula)*,type?)>
    <!ATTLIST property name CDATA #REQUIRED>
    <!ATTLIST property node CDATA #IMPLIED>
    <!ATTLIST property access CDATA #IMPLIED>
    <!ATTLIST property type CDATA #IMPLIED>
    <!ATTLIST property column CDATA #IMPLIED>
    <!ATTLIST property length CDATA #IMPLIED>
    <!ATTLIST property precision CDATA #IMPLIED>
    <!ATTLIST property scale CDATA #IMPLIED>
    <!ATTLIST property not-null (true|false) #IMPLIED>
    <!ATTLIST property unique (true|false) "false">
    <!ATTLIST property unique-key CDATA #IMPLIED>
    <!ATTLIST property index CDATA #IMPLIED>                <!-- include the columns spanned by this property in an index -->
    <!ATTLIST property update (true|false) #IMPLIED>
    <!ATTLIST property insert (true|false) #IMPLIED>
    <!ATTLIST property optimistic-lock (true|false) "true"> <!-- only supported for properties of a class (not component) -->
    <!ATTLIST property formula CDATA #IMPLIED>
    <!ATTLIST property lazy (true|false) "false">
    <!ATTLIST property generated (never|insert|always) "never">

<!ELEMENT id (meta*,column*,type?,generator?)>行说明<id>代码可以包含<generator>代码,但代码<property>可以包含{{1}}代码。等等等......