views:

163

answers:

5

Why it isn't enough to set the @Entity annotation?

Am I missing the point here (performance?)?

Thanks.

+2  A: 

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.

Chandra Patni
+2  A: 

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.

Mike Q
+2  A: 

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.

skaffman
+1  A: 

By default all properly annotated classes and all hbm.xml files found inside the archive are added to the persistence unit configuration. You can add some external entity through the class element though.

Hibernate EntityManager Reference Docs

Adeel Ansari
A: 

Thanks, it's much clearer to me now. Happy holidays!

MisterY