applicationContext.xml with datasource or hibernate.cfg.xml. Difference? applicationContext.xml with datasource or hibernate.cfg.xml. Difference? spring spring

applicationContext.xml with datasource or hibernate.cfg.xml. Difference?


Answer 1:

Both approaches are the same. By default , hibernate reads the configuration from classpath:hibernate.cfg.xml to build SessionFactory . LocalSessionFactoryBean just allows you to setup hibernate configuration inside applicationContext.xml instead of hibernate.cfg.xml .

If a same property is specified in both files , depending on the property , it will has addictive effect or the properties specified in applicationContext.xml will take higher priority such that those values in hibernate.cfg.xml will be ignored.

For method 1, annotatedClasses and hibernateProperties should have the addictive effect with the corresponding values in hibernate.cfg.xml . The DBCP dataSouruce in applicationContext.xml should cause the related properties in hibernate.cfg.xml being ignored.

Answer 2:

For method 2 , if you don't specify any properties of LocalSessionFactoryBean , all the hibernate configurations are specified by the hibernate.cfg.xml. If there are no connection pool configured in hibernate.cfg.xml , hibernate's own connection pooling algorithm is used by default , which is quite rudimentary and not intended for use in a production system, or even for performance testing.


If what you want is to build a session factory, you will get the same result with both approaches. I don't think one can do more than the other.

In my opinion, you would use the hibernate.cfg.xml approach when you are not using Spring. When JUnit testing your DAOs for example. Not having to build a Spring application context makes your tests run faster.

However, when you are using Spring, I think it's a good thing to keep your datasource separated from the session factory. You are using Spring for dependency inject, right? Why not using spring to give your session factory what it needs?