I want to configure hibernate in spring...for that I am using following configurations in spring-servlet.xml
<context:property-placeholder location="classpath:resources/database.properties" />
<bean class="org.springframework.jdbc.datasource.DriverManagerDataSource" id="dataSource">
<property name="driverClassName" value="${database.driver}"></property>
<property name="url" value="${database.url}"></property>
<property name="username" value="${database.user}"></property>
<property name="password" value="${database.password}"></property>
</bean>
here is my database.properties file
database.driver=com.mysql.jdbc.Driver
database.url=jdbc:mysql://10.2.5.142:3306/testdb
database.user=root
database.password=
hibernate.dialect=org.hibernate.dialect.MySQLDialect
hibernate.show_sql=true
hibernate.hbm2ddl.auto=update
Now I want to use only single instance of SessionFactory ; for that I included following code in my DAO class
SessionFactory sessionFactory = new Configuration().configure("/resources/hibernate.cfg.xml").buildSessionFactory();
I must have to set Database related parameters at two places
(1) database.properties
(2) hibernate.cfg.xml
Is there any way by which I can put those values only at single place
You don't need the
hibernate.cfg.xml
file at all. You can configure yourSessionFactory
as aSpring
bean.here an example :
You can import that configuration in your
spring-servlet.xml
by using the import tag.And then, inject your SessionFactory instead of instantiate it by yourself.
You can use a
LocalSessionFactoryBean
to set properties and inject a DataSource instead of usinghibernate.cfg.xml
, see http://docs.spring.io/spring/docs/3.2.5.RELEASE/spring-framework-reference/htmlsingle/#orm-hibernateHere is an example from the Spring Reference: