Hibernate and Eclipse Integration

Recently I had the experience of converting a Java project in Eclipse 3.1 to a plugin and RCP. Previously working Hibernate activity failed with errors indicating that the hibernate.cfg.xml file could not be located. This led me on massive flailing with plugin classpaths, to no avail, since this was not the problem.

 

The Eclipse class loading mechanism and problems with integrating with third party libraries has been the subject of much discussion, and previous solutions have involved using Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader()) in the appropriate places, which are not obvious to me nor to most naive users. However, Eclipse 3.1 has a "buddy loading" facility that solves this problem nearly trivially. Credit for telling me the solution belongs to snpesnpe, but is presented here to help with this problem.

 

The issue is that the Hibernate libraries cannot know, in advance, where a user will install relevant code, particularly the hibernate.cfg.xml and related hbm.xml files. Placing the hibernate.cfg.xml file at the root of the classpath is the usual solution, but since the Hibernate libraries don't even know that your plugin exists, there is no way for them to know what classpath to explore for this file. Enter the buddy system.

 

In the MANIFEST.MF file of the Hibernate plugin (which NEEDS the buddy loading), such as org.hibernate.eclipse, add a line:

Eclipse-BuddyPolicy:registered

and in the MANIFEST.MF file of your plugin project or RCP project, add the line:

Eclipse-RegisterBuddy:org.hibernate.eclipse

 

Important to notice the syntax - our plugin is willing to be seen by the hibernate library, using Eclipse-RegisterBuddy, and Hibernate is registering itself with Eclipse-BuddyPolicy. While this is stated clearly in the Eclipse Help (in retrospect!) it is critical to get the syntax precisely correct.

Finally, if you are using HibernateUtil as your main entry point into Hibernate, then in your plugin start method add the line:

Class.forName("myPlugin.HibernateUtil"); //full class name should go here

This works - assumption is that hibernate.cfg.xml is in the src directory of your plugin and this is in the classpath.