Hibernate: Migrating from mapping to annotations - is it possible to mix hbm and annotation?

marcam picture marcam · Jul 4, 2012 · Viewed 11.5k times · Source

I'm currently migrating my project from Hibernate HBM Mappings to Annotations. Everything was easy as far as i dealt with small classes. But I have same huge classes and i try to mix both mapping and annotations for this class. I read that this was possible by using the hibernate property "hibernate.mapping.precedence" and setting it to "class, hbm" instead of "hbm, class". (see: In Hibernate: is it possible to mix Annotations and XML configuration for an Entity?)

For example I have the following Document class:

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

and the following Document.hbm.xml file:

<?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>

In my hibernate.cfg.xml file I put:

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

My problem is that: - if I put "class, hbm" for the precedence then I have ONLY my annotations in class Document - if I put "hbm, class" then I have ONLY my mappings in the hbm ressource

Does anyone knwo if there is a way to have both Annotations and HBM mappings ?

Thanks

Kamran

PS: I use : Hibernate 4.1.4 and Spring Framework 3.1.1

Answer

Pablo picture Pablo · Jul 4, 2012

You can't mix them for the same class. At the end of section 1.2 of hibernate annotations:

You can mix annotated persistent classes and classic hbm.cfg.xml declarations with the same SessionFactory. You can however not declare a class several times (whether annotated or through hbm.xml). You cannot mix configuration strategies (hbm vs annotations) in an entity hierarchy either.

To ease the migration process from hbm files to annotations, the configuration mechanism detects the mapping duplication between annotations and hbm files. HBM files are then prioritized over annotated metadata on a class to class basis. You can change the priority using hibernate.mapping.precedence property. The default is hbm, class, changing it to class, hbm will prioritize the annotated classes over hbm files when a conflict occurs.

Using annotations and hbm files is declaring a class two times. Therefore, one will be prioritized over the other in a class to class basis (class to class basis means that for each class, only the hbm file or the annotations are used).