Wednesday, June 26, 2013

Java; Hibernate; apply prefix to database tables

My current project uses two collections of tables.  One set is maintained by one application.  The other set by another.  I won't explain why they are not using separate databases so that the same table names may be used.  I admit, that would be a better solution.  Or even using different schemas.  Instead, one collection is differentiated by a table prefix and the other doesn't have one.

How can this be accomplished with minimal impact to the source code so that common libraries may be shared between the two applications?  A NamingStrategy class did the job nicely.

Hibernate Community Documentation: Configuration: 3.6. Implementing a NamingStrategy
http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html/session-configuration.html#configuration-namingstrategy

The only difference in setting up the SessionFactory for each application was to add one line in the Configuration setup.  Not very invasive and I have been able to reuse a lot of code, including all my DAOs and Hibernate annotations.

When setting up Hibernate, I pretty much followed the example listed under 'Create Application Class'.  I didn't need to include lib/ejb3-persistence.jar (listed as required under 'Environment Setup for Hibernate Annotation') as it appears to be included in the Maven resources listed in its associated pom.xml file.
      <dependency>
          <groupId>org.hibernate</groupId>
          <artifactId>hibernate-core</artifactId>
          <version>4.1.4.Final</version>
      </dependency>

      <dependency>
          <groupId>org.hibernate.common</groupId>
          <artifactId>hibernate-commons-annotations</artifactId>
          <version>4.0.1.Final</version>
      </dependency>

Additional Resources

No comments:

Post a Comment