Why I have to declare each and every class in my hibernate.cfg.xml when using annotations?

The annotation is not enough because hibernate does not know where your annotated classes live without some sort of explicit declaration. It could, in theory, scan every single class in the classpath and look for the annotation but this would be very very expensive for larger projects.

You can use spring which has a helper that can allow you to specify the package(s) that your hibernate objects are in and it will just scan these packages for @Entity. If you have all your objects in a small number of fixed packages this works well.

E.g.

  <bean id="referenceSessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
    <property name="dataSource" ref="dataSource"/>
    <property name="packagesToScan">
      <array>
        <value>com.xxx.hibernate.objects</value>
      </array>
    </property>
  </bean>

The above is the Spring declaration. If you aren't familiar with the above syntax you can just construct it programmatically.

AnnotationSessionFactoryBean sfb = new AnnotationSessionFactoryBean();
sfb.setDataSource( ds );
sfb.setHibernateProperties( hibProps);
sfb.setPackagesToScan( ... );
sfb.initialise();
SessionFactory sf = sfb.getObject();

It supports a bunch of config options so you can use raw properties or pass in a pre-config'd datasource.


You don't if you set hibernate.archive.autodetection property to true. There is a performance issue here as Hibernate will search the jar files for the JPA annotation. Note that, it will also initializes those classes.


Yes :)

The hibernate.cfg.xml file is not used to specify your entities, it's used to configure things like hibernate's connection parameters and global settings. The hibernate.cfg.xml file also contains instructions on how to locate the entities. You can list the XML mapping files using <mapping resource=XYZ>, but if you're using JPA annotations like @Entity, then this is unnecessary, Hibernate will auto-detect them.

You can mix annotations and mapping XML if you choose, but that's by no means necessary in most situations.