JDBC, Transactions, Spring Data JPA
July 30, 2021
M03 Q21 What do you need to do in Spring if you would like to work with JPA?
Following steps are required to work with JPA in Spring Framework:
1 Declare maven dependencies:
- JPA API -
javax.persistence:javax.persistence-api
- Spring ORM -
org.springframework:spring-orm
- ORM of your choice, for example -
org.hibernate:hibernate-core
- Database Driver, for example -
org.hsqldb: hsqldb
- Optionally, but recommended, Spring Data JPA -
org.springframework.data:spring-data-jpa
2 Define DataSource Bean
Also, I have JpaConfiguration. Here I added @EnableJpaRepositories annotation. It is a part of spring-data and it's not required but I want to generate DAO automatically.
3 Define PlatformTransactionManager, in case of JPA JpaTransactionManager
4 Define EntityManagerFactoryBean
LocalContainerEntityManagerFactoryBean
for standalone applicationEntityManagerFactory
from JNDILocalEntityManagerFactoryBean
for Test purposes
Here I defined LocalContainerEntityManagerFactoryBean
because I am creating a standalone application. I pointed to the package which contains data objects at setPackageToScan
method. And created JpaTransactionManager
bean.
5 Define @Entity
classes with at least on @Id
field
6 Define DAO classes, or use Spring Data JPA Repositories