【问题标题】:Hibernate: Migrating from mapping to annotations - is it possible to mix hbm and annotation?Hibernate:从映射迁移到注释 - 是否可以混合使用 hbm 和注释?
【发布时间】:2012-07-04 16:27:13
【问题描述】:

我目前正在将我的项目从 Hibernate HBM Mappings 迁移到 Annotations。 就我处理小班而言,一切都很容易。 但是我有同样庞大的类,我尝试为这个类混合映射和注释。我读到这可以通过使用休眠属性“hibernate.mapping.precedence”并将其设置为“class,hbm”而不是“hbm,class”来实现。 (见:In Hibernate: is it possible to mix Annotations and XML configuration for an Entity?

例如,我有以下 Document 类:

@Entity
@Table(name="DOCUMENT")
public class Document  {
   @Column(name="DESCRIPTION")
   private String description;
}

以及以下 Document.hbm.xml 文件:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN" 
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">    
<hibernate-mapping>
  <class name="Document" table="DOCUMENT" >
    <id name="id" column="DOCUMENT_ID" type="long" />
  </class>
</hibernate-mapping>

在我的 hibernate.cfg.xml 文件中我放了:

<property name="hibernate.mapping.precedence">class, hbm</property>
<mapping class="Document"/>
<mapping resource="Document.hbm.xml"/>

我的问题是: - 如果我把“类,hbm”作为优先级,那么我在类文档中只有我的注释 - 如果我输入“hbm,class”,那么我在 hbm 资源中只有我的映射

有没有人知道是否有办法同时拥有注解和 HBM 映射?

谢谢

卡姆兰

PS:我使用的是:Hibernate 4.1.4 和 Spring Framework 3.1.1

【问题讨论】:

  • 如何解决?

标签: java spring hibernate annotations hibernate-mapping


【解决方案1】:

您不能将它们混合用于同一个班级。结尾处section 1.2 of hibernate annotations

您可以将带注释的持久类和经典的 hbm.cfg.xml 声明与相同的 SessionFactory 混合使用。 您不能多次声明一个类(无论是注释还是通过 hbm.xml)。您也不能在实体层次结构中混合配置策略(hbm 与注释)。

为了简化从 hbm 文件到注解的迁移过程,配置机制会检测注解和 hbm 文件之间的映射重复。然后,HBM 文件优先于带注释的元数据在类与类的基础上。您可以使用 hibernate.mapping.precedence 属性更改优先级。默认是hbm,class,改成class,hbm会在发生冲突时优先标注的classes优先于hbm文件。

使用注解和 hbm 文件是两次声明一个类。因此,在类到类的基础上,一个将优先于另一个(类到类的基础意味着对于每个类,仅使用 hbm 文件或注释)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多