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
    


Friday, September 17, 2010

Spring Exception:delaying identity-insert due to no transaction in progress

I kicked off a new project by copying the code generated from Spring Roo and it worked pretty well at beginning. However, when I begin the web layer (Spring MVC Controller), strange things happen.

The problem is, the Controller cannot use Service layer to persist data into database. But the Unit Test does not have this problem. I turn on debug and check the log file carefully. In the place where data should inert into database, I find the information: "delaying identity-insert due to no transaction in progress".

Spring Roo use AspectJ to manage transcation and it requires some job in compiling time. So we need to add aspectj-maven-plugin to build this project.


    org.codehaus.mojo
    aspectj-maven-plugin
    1.3
    
     
      org.aspectj
      aspectjrt
      ${aspectj.version}
     
     
      org.aspectj
      aspectjtools
      ${aspectj.version}
     
    
    
     
      
       compile
       test-compile
      
     
    
    
     true
     
      
       org.springframework
       spring-aspects
      
     
     1.6
     1.6