Friday, June 6, 2008

Hibernate Annotations: what they don't tell you about mapping a package

I just spent some time setting up a project using hibernate-annotations.

In the reference documentation you find the following example for hibernate.cfg.xml:

<hibernate-configuration>
    <session-factory>
            <mapping package="test.animals"/>
            <mapping class="test.Flight"/>
            <mapping class="test.Sky"/>
            <mapping class="test.Person"/>
            <mapping class="test.animals.Dog"/>
            <mapping resource="test/animals/orm.xml"/>
     </session-factory>
</hibernate-configuration>

What they don't tell you is what the element <mapping package="test.animals"/> means...

Intuitively I would expect, that any annotated class in the given package is picked up automatically by the session factory, so that you can save the work of explicitly enlisting them.

But this is not the case! And I could not find any clear documentation why...

I only found the following clues:

  • According to this documentation, a package can be annotated. I never heard of this. It seems that you have to place the annotations in a file called package-info.java.
    Here is an example, using annotated packages.
  • According to the api documentation of the class AnnotationConfiguration, the method addPackage 'reads package level metadata'.

So I guess the element <mapping package="test.animals"/> picks up any annotation-configuration that's available on the given package. But it does not pick up any configuration of the classes in the package...

This is still a speculation on my part, but I think I am not the only one tripping over this ...

2 comments:

  1. You are right by saying you are not the only one who tripped over this, me too. It is such a confusing mapping style.

    ReplyDelete
  2. I agree, you are not the only one at all... Thank you for your clues!

    ReplyDelete

Related Posts Plugin for WordPress, Blogger...