JPA was proved a greate success in Java community, and it is wildly used in Java applications, including some desktop applications.
Spring embraces JPA specification in the first instance.
We have configured a DataSource, to support JPA in Spring, we need to configure a JPA specific EntityManagerFactoryBean and a PlatformTransactionManager.
The transaction-type is RESOUECE_LOCAL, another available option is JTA. Most of the time, Spring applications is running in a Servlet container which does not support JTA by default.
You have to specify entity classes will be loaded and datasource here. Spring provides an alternative, LocalEntityManagerFactoryBean to simplify the configuration, there is a setPackagesToScan method provided to specify which packages will be scanned, and another setDataSource method to setup Spring DataSource configuration and no need to use database connection defined in the persistence.xml file at all.
More simply, LocalContainerEntityManagerFactoryBean does not need a persistence.xml file any more, and it builds JPA environment from ground. In above codes, we use LocalContainerEntityManagerFactoryBean to shrink JPA configuration.
Next, configure Spring Data JPA, add spring-data-jpa into pom.xml.
<!-- Spring Data -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-commons</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
</dependency>
Enable Spring Data JPA, use a standalone configuration class.
Spring Data Commons provides a series of Repostory APIs. basePackages in @EnableJpaRepositories will tell Spring Data JPA to scan Repository classes in these packages.
Do not forget to add JpaConfig and DataJpaConfig configuration classes into getRootConfigClasses method of AppInitializer.