Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 840
MisterY Avatar asked Dec 24 '09 09:12

MisterY


People also ask

Is it mandatory to have this option in hibernate CFG XML?

Try removing that and hibernate will not look for the non-existent file. Basically you are setting all the required properties via your properties object so there is no real need to tell Hibernate to look for a hibernate. cfg. xml file which is exactly what the configure() method does.

Can we have more than one hibernate CFG XML?

Yes, you can.

What happens when both hibernate properties and hibernate CFG XML are in the classpath?

If both hibernate. properties and hibernate. cfg. xml files are present in the classpath then hibernate.

What does hibernate CFG XML contain?

hibernate. cfg. xml file contains database related configurations and session related configurations. Database configuration includes jdbc connection url, DB user credentials, driver class and hibernate dialect.


2 Answers

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.

like image 59
Mike Q Avatar answered Oct 19 '22 10:10

Mike Q


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.

like image 38
Chandra Patni Avatar answered Oct 19 '22 10:10

Chandra Patni