MisterY
MisterY

Reputation: 445

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

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

Am I missing the point here e.g. performance?

Upvotes: 8

Views: 4845

Answers (4)

Adeel Ansari
Adeel Ansari

Reputation: 39907

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

Upvotes: 1

skaffman
skaffman

Reputation: 403481

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.

Upvotes: 2

Mike Q
Mike Q

Reputation: 23229

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.

Upvotes: 8

Chandra Patni
Chandra Patni

Reputation: 17577

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.

Upvotes: 3

Related Questions