Sunday, September 19, 2010

Mix annotation with orm.xml mapping in JPA

There has been a long time debate about whether annotations were better or worse than XML. But it is necessary to mix annotation with XML mapping in JPA sometimes. In fact, XML mapping usage is defined to allow annotations to be used and then overridden by XML. This provides the ability to use annotations for some things and XML for others, or to use annotations for an expected configuration but then supply an overriding XML file to suit a particular execution environment.

First of all, we need to understand the metadata-collection process, from both annotation and XML file.

  • 1. Process the annotation.
  • 2. Add the classes defined in XML. Override if the class-level metadata if existed in annotation.
  • 3. Add the attribute mappings defined in XML. Override if the attribute-level metadata if existed in annotation.
  • 4. Apply defaults.


Step1: To employing XML mapping in JPA, we need to create a orm.xml fle




 XML definition Example

 
  

Step2: add xml definition in persistence.xml:



 
        org.hibernate.ejb.HibernatePersistence
        
            
            
            
            
        
        
 orm.xml
    


0 comments: