Java and Technology weblog
I recently converted a project I have been working on to use Maven. After setting up all the dependencies in the pom, I got everything compiling fine but ran into problems getting the unit tests to pick up the hibernate config (hibernate.cfg.xml) and hibernate mapping (*.hbm.xml) files. With hindsight, it is straightforward, but it took me a while to figure it out so I thought I’d post the solution here.
Initially, I had my hibernate.cfg.xml file in the following directory
And when I first tried to run my hibernate unit tests (mvn test), I got this error:
SessionFactory creation failed.org.hibernate.HibernateException: /hibernate.cfg.xml not found
Some checking of the maven docs and some forums revealed the following possible solutions:
1) Copy the hibernate.cfg.xml file to
This works, however I think it is a hack as the target folder is generated rather than being somewhere you should actually manually create files.
2) The next solution I found suggested moving the hibernate.cfg.xml to
This works well as the contents of this folder are copied to the base level of the my-app/target/classes folder so it is basically a ‘more correct’ solution than the first.
3) The next and I think best solution was to create a new, duplicate hibernate.cfg.xml inside
This allows a different hibernate.cfg.xml file to be used for testing and, for example, facilitates connecting to a different database (such as hsqldb) for testing while continuing to use your regular database (such as MySQL) for the app itself.
A couple of points to note:
1) The hibernate mapping files (i.e. the *.hbm.xml files) should also be in the resources folder (in whatever directory structure you choose) to ensure that these too are accessible by the unit tests.
2) I am not (yet) using Spring with the hibernate components, which would likely have changed the above setup.