gpt4 book ai didi

java - Hibernate:从映射迁移到注释 - 是否可以混合使用 hbm 和注释?

转载 作者:IT老高 更新时间:2023-10-28 13:46:51 26 4
gpt4 key购买 nike

我目前正在将我的项目从 Hibernate HBM Mappings 迁移到 Annotations。就我处理小类而言,一切都很容易。但是我有同样巨大的类,我尝试为这个类混合映射和注释。我读到这可以通过使用 hibernate 属性“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

最佳答案

您不能将它们混合用于同一类。在 section 1.2 of hibernate annotations 结尾:

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

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

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

关于java - Hibernate:从映射迁移到注释 - 是否可以混合使用 hbm 和注释?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11332698/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com