If you use Spring 2 or 3 along with Hibernate and take advantage of the wonderfully declarative annotation development style, you probably have had this same problem as I have. Say you have defined your model objects with hibernate EJB 3 style annotations for your main database. Now perhaps you have several satellite databases that differ slightly from the main database to fulfill auxiliary roles.

You certainly wouldn’t want to package and provide an additional model objects library for the application or specific context using one of these auxiliary databases. Luckily, there is a rather simple solution. Hibernate allows you to override any annotations by providing an XML definition and specifying it in your configuration. The Spring Framework also provides access to this through their applicationContext.xml files during the session factory and DataSource configuration points.

Essentially, you can have a set of overrides for every application context you load allowing access to multiple different databases using the same model library.

My Specific Situation

In my case, I had a well defined @Id column that provided a cross database sequence or identity population using the AUTO generator type provided by the Hibernate libraries. In one of our applications we had a case where the main database was used to create this record, but a duplicate needed to exist on the outside database to fulfill database integrity constraints on an additional table. Sparing, the specific implementation details (which could probably been avoid with better original design), I needed to disable the generator on this object for this application context.

Here is the default configuration as defined based on the main

@Id
@Column(name = "object_id")
@GeneratedValue(strategy = GenerationType.AUTO, generator="some_sequence")
private Integer id;

Here is the XML hibernate mapping override file created in my src/main/webapp/WEB-INF directory along with the application context XMLs for the Spring 3 configuration:


    
      

      
    
  


One important configuration to note is the ‘metadata-complete’ attribute on the entity tag. This attribute defines whether to throw away other configuration metadata defined with annotations on the object and use your configuration exclusively. To do simple overrides this is definitely not the intended action.

To enable the configuration file in spring, the following snippet shows what was added to the application context:




      
    


org.hibernate.dialect.PostgreSQLDialect
true
false
      
    


            com.xxx.persistence.a.object
            com.xxx.persistence.b.object
        
    

      WEB-INF/hibernate-mapping-overrides.xml
    
  
© 2011 Technical Solutions Suffusion theme by Sayontan Sinha