- First we tell spring that we want to use classpath scanning for Spring components (Services, DAOs) rather than defining them one by one in spring xml. We have also enabled Spring annotation detection.
- Adding the datasource, that is currently HSQLDB in-memory database.
- We set up a JPA
EntityManagerFactory
that will used by the application to obtain an EntityManager. Spring supports 3 different ways to do this, we have used LocalContainerEntityManagerFactoryBean
for full JPA capabilities.We set LocalContainerEntityManagerFactoryBean
attributes as:- packagesToScan attribute that points to our model classes package.
- datasource defined earlier in spring configuration file.
- jpaVendorAdapter as Hibernate and setting some hibernate properties.
- We create Spring PlatformTransactionManager instance as a JpaTransactionManager. This transaction manager is appropriate for applications that use a single JPA EntityManagerFactory for transactional data access.
- We enable the configuration of transactional behavior based on annotations, and we set the transactionManager we created.
Spring ORM Hibernate JPA Example Test Program
Our spring ORM JPA Hibernate example project is ready, so let’s write a test program for our application.

You can see how easily we can start the Spring container from a main method. We are getting our first dependency injected entry point, the service class instance. ProductDao
class reference injected to the ProductService
class after the spring context is initialized.
After we got ProducService
instance, we can test it’s methods, all method call will be transactional due to Spring’s proxy mechanism. We also test rollback in this example.
If you run above spring ORM example test program, you will get below logs.
Copy

Note that the second transaction is rolled back, this why product list didn’t changed.
If you use log4j.properties
file from attached source, you can see what’s going on under the hood.
References:
http://docs.spring.io/spring/docs/current/spring-framework-reference/html/orm.html
You can download the final Spring ORM JPA Hibernate Example project from below link and play around with it to learn more.