rainer198
rainer198

Reputation: 3263

Spring + Hibernate Session Factory: Mapping File Directory Inside a JAR

I have web project based on Hibernate and Spring (programmatic configuration). The Hibernate mappings are provided in a package which is archived in a JAR.

When it comes to initialize the session factory I used to call:

sessionFactory.
    setMappingDirectoryLocations(new Resource[]{
        new ClassPathResource("org/all/theway/to/hibernatemappings")});

in order to tell Hibernate where to look for mapping files. "org/all/theway/to/hibernatemappings" is the package which contains the hbm.xml files. This worked fine within Eclipse (GWT dev mode), as the mapping-containing project is also checked out and linked to my web project. However, once I create a war and deploy it to Tomcat, it fails to get the class path resource.

Spring's ClasspathResource javadoc implies this: "Supports resolution as java.io.File if the class path resource resides in the file system, but not for resources in a JAR. Always supports resolution as URL. "

But what to do instead? I could also use setMappingJarLocation instead, but I do not like to hardcode a jar file name in my Spring context. Further, when I tried it, it also only worked within IDE, but inside Tomcat the same file path (WEB-INF/lib/file.jar) did not work. This also makes me believe that this would be an ugly solution.

Is there a workaround which works without using the jar file?

Upvotes: 0

Views: 2676

Answers (2)

Adisesha
Adisesha

Reputation: 5268

This works

//All application contexts implements ResourcePatternResolver

ResourcePatternResolver resourcePatternResolver= applicationContext;
sessionFactory.setMappingDirectoryLocations(resourcePatternResolver.getResources("classpath*:org/all/theway/to/hibernatemappings/*.hbm.xml"));

EDIT: Replaced DefaultResourceLoader with ResourcePatternResolver.

Upvotes: 1

rainer198
rainer198

Reputation: 3263

Not really a solution of the original problem but a workarounnd which avoids dealing with filesystem file names of jar files within the configuration code:

I simply told ant to unpack the JAR in question into the WEB-INF/classes folder

<target name="unpack.hibernatemappings">
    <unzip dest="${war.dir}/WEB-INF/classes">
        <fileset dir="${lib.dir}">
            <include name="archive-containing-the-hbm-files.jar"/>
        </fileset>
    </unzip>
</target>

Now, the Hibernate mappings reside in the file system and can be accessed as ClassPathResource (like in the questions's example).

Upvotes: 0

Related Questions