Spring factory method

Today I am going to write about a small trick that I have used recently. Lets imagine following problem: we are using JPA (Hibernate) and Spring together.

<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
	<property name="persistenceUnitName" value="testPU" />
	<property name="dataSource" ref="dataSource" />
	<property name="jpaProperties">
			<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>

It works nice, without any problem. But imagine that one day you need to access Hibernate statistics. To achieve this, you have to have access to the Hibernate session factory. But we have no session factory here, we are using the entity manager which hides session factory underneath. How to access it? The solution is simple, you can use factory method.

<!-- Publishing session factory to be able view statistics -->
<bean id="sessionFactory" factory-bean="entityManagerFactory" factory-method="getSessionFactory" />

By this simple code we say to Spring: Hey, just call the method getSessionFactory on the entityManagerFactory bean and store the result as a bean with name sessionFactory. Since we are using Hibernate as the JPA provider, entityManagerFactory is instance of HibernateEntityManagerFactory and by a chance it has getSessionFactory method. Now we have access to the session factory and we can use it however we like.

Note: If you wonder why the hell I have started to write in something that looks almost like English when apparently I do even more mistakes than in Czech, the answer is simple. I just need to practice my English (apart from that I want to be world famous, not just known in Czech Republic)

3 thoughts on “Spring factory method

  1. Chris

    yes excellent tip and you are now famous in my small part of the UK.

Comments are closed.