SlideShare a Scribd company logo
How to configure JPA/Hibernate
for a Spring application
This is a reference/document for developers to understand how
JPA/Hibernate is configured for a Spring application.
Jayasree Perilakkalam
Introduction
• This is a reference/document that covers how to configure
JPA/Hibernate in a Spring application
• In this reference documentation, Maven has been used for
dependency management.
• Any questions/suggestions/comments are welcome via the comments
section below.
Maven Dependency Configuration
• Add the following in pom.xml file
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.4.4.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate.javax.persistence/hibernate-jpa-2.1-api -
->
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.1-api</artifactId>
<version>1.0.2.Final</version>
</dependency>
Annotations used
• @Repository
- This annotation acts as a marker for a class that fulfills the role/stereotype of a
repository (DAO layer).
- This is a Spring stereotype annotation and is a specialized @Component annotation.
It has @Component annotation within it and thus enables auto discovery of the
Spring bean.
- Additional to indicating that it is an annotation based configuration, it provides
automatic exception translation in the persistence layer when used with the
following in the Spring’s application context.
@Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation(){
return new PersistenceExceptionTranslationPostProcessor();
}
- Spring Data JPA repository layer(interfaces) are annotated with @Repository
Annotations used
• @EnableTransactionManagement
- This is used in a @Configuration class to enable transactional support.
• @Transactional
- After the transaction is configured (steps provided in the next couple of slides), this
annotation can be added at the class level or the method level to achieve transaction
management. Further configuration via the following properties is possible:
- propogation Type
- isolation Level
- Timeout of the operation in @Transactional in seconds
- readOnly flag
- the Rollback rules
- Only public methods can be annotated with @Transactional. The methods with other
visibilities will silently ignore this annotation.
- Spring creates proxies for all the classes annotated with @Transactional (either at the class
level or the method level). The proxy allows Spring to add transactional logic before and after
running the method, etc.
Understanding EntityManagerFactory
• EntityManagerFactory facilitates instantiation of EntityManager
instances
• EntityManagerFactory is constructed for a specific database and it
provides an efficient way to construct multiple EntityManager
instances for that database.
• EntityManager is a Java interface (part of JPA) and is responsible for
starting the particular transaction (EntityTransaction) and managing
the persistence operations on entities/objects. EntityTransaction has
a one to one relationship with EntityManager. Entity is the
persistence objects (stores as records in the database).
Configure EntityManagerFactory
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean() {
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource());
em.setPackagesToScan(new String[] { "com.example.entity" }); // --- package where entity classes exist
JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(vendorAdapter);
em.setJpaProperties(additionalProperties());
return em;
}
// ...
Understanding Spring Framework’s
PlatformTransactionManager
• PlatformTransactionManager provides transaction
abstraction/transaction strategy.
• PlatformTransactionManager is a service provider interface(SPI).
• JpaTransactionManager (Spring Framework) is an implementation of
PlatFormTransactionManager for a single JPA EntityManagerFactory.
It binds a JPA EntityManager from the specified factory to the thread,
allowing only one-thread bound EntityManager per factory.
Configure TransactionManager
@Bean
public PlatformTransactionManager transactionManager(){
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(
entityManagerFactoryBean().getObject() );
return transactionManager;
}
JNDI DataSource Lookup
• Retrieve DataSource from Tomcat Application Server’s context.xml file
@Bean
public DataSource dataSource() {
JndiDataSourceLookup aJndiDataSourceLookup = new JndiDataSourceLookup();
aJndiDataSourceLookup.setResourceRef(true);
DataSource aDataSource = aJndiDataSourceLookup.getDataSource(“java:comp/env/jdbc/myoracle”)
return aDataSource;
}
• Configure JNDI Datasource in Tomcat by adding a declaration of the resource in
the context.xml file. A sample is as follows:
<Resource name="jdbc/myoracle" auth="Container"
type="javax.sql.DataSource" driverClassName="oracle.jdbc.OracleDriver"
url="jdbc:oracle:thin:@127.0.0.1:1521:mysid"
username="scott" password="tiger" maxTotal="20" maxIdle="10"
maxWaitMillis="-1"/>
Additional Hibernate properties set up
private Properties additionalProperties() {
Properties properties = new Properties();
….
….
return properties;
}
Note: PropertiesLoaderUtils (Spring Framework) can be used to load properties
from a file.
A sample configuration file
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(basePackages= “com.example.repository”) //  [will scan the package specified
here for Spring Data repositories. So this is a Spring Data annotation/configuration ]
public class PersistExampleConfig {
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean() {
….
}
@Bean
public PlatformTransactionManager transactionManager(){
…
}
Contd…
A sample configuration file
Contd …
@Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation(){
…
}
@Bean
public DataSource dataSource() {
….
}
private Properties additionalProperties() {
…
}
}
JPA Annotations
• Following are some important JPA annotations (for object relational
mapping i.e. ORM)
- @Entity
- @Table
- @Id
- @Column
- @JoinColumn
- @ManytoOne
Note: I will cover JPA annotations in detail in a separate presentation.
Conclusion
• We can use @EnableJpaAuditing to enable auditing. This is a Spring
Data annotation to enable auditing. I will cover this in a separate
presentation.
• This is a reference/document to understand Hibernate/JPA
configuration in a Spring application
• This will help developers to build transactional applications faster.
Thank you

More Related Content

What's hot (20)

PPT
Hibernate architecture
Anurag
 
PPT
jpa-hibernate-presentation
John Slick
 
PPS
Jdbc api
kamal kotecha
 
PPTX
Spring & hibernate
Santosh Kumar Kar
 
PPTX
Introduction to JPA Framework
Collaboration Technologies
 
PPTX
jsp MySQL database connectivity
baabtra.com - No. 1 supplier of quality freshers
 
PPTX
Hibernate ppt
Aneega
 
PPTX
Advance java session 5
Smita B Kumar
 
PPTX
Hibernate in Action
Akshay Ballarpure
 
DOC
Hibernate tutorial for beginners
Rahul Jain
 
PPT
Entity Persistence with JPA
Subin Sugunan
 
PPTX
Introduction to jQuery
Collaboration Technologies
 
PDF
Java persistence api 2.1
Rakesh K. Cherukuri
 
PPTX
Hibernate
Prashant Kalkar
 
PPTX
Java database connectivity
Atul Saurabh
 
ODP
Hibernate complete Training
sourabh aggarwal
 
DOC
24 collections framework interview questions
Arun Vasanth
 
PPT
Hibernate presentation
Manav Prasad
 
PPTX
Hibernate Basic Concepts - Presentation
Khoa Nguyen
 
PDF
Lecture 3: Servlets - Session Management
Fahad Golra
 
Hibernate architecture
Anurag
 
jpa-hibernate-presentation
John Slick
 
Jdbc api
kamal kotecha
 
Spring & hibernate
Santosh Kumar Kar
 
Introduction to JPA Framework
Collaboration Technologies
 
jsp MySQL database connectivity
baabtra.com - No. 1 supplier of quality freshers
 
Hibernate ppt
Aneega
 
Advance java session 5
Smita B Kumar
 
Hibernate in Action
Akshay Ballarpure
 
Hibernate tutorial for beginners
Rahul Jain
 
Entity Persistence with JPA
Subin Sugunan
 
Introduction to jQuery
Collaboration Technologies
 
Java persistence api 2.1
Rakesh K. Cherukuri
 
Hibernate
Prashant Kalkar
 
Java database connectivity
Atul Saurabh
 
Hibernate complete Training
sourabh aggarwal
 
24 collections framework interview questions
Arun Vasanth
 
Hibernate presentation
Manav Prasad
 
Hibernate Basic Concepts - Presentation
Khoa Nguyen
 
Lecture 3: Servlets - Session Management
Fahad Golra
 

Similar to Configuring jpa in a Spring application (20)

DOC
Sel study notes
Lalit Singh
 
PDF
Introduction to Datastore
Software Park Thailand
 
PDF
Spring Boot Tutorial Part 2 (JPA&Hibernate) .pdf
abdelr7man3mad2004
 
PDF
Java Web Programming on Google Cloud Platform [2/3] : Datastore
IMC Institute
 
PDF
Data access
Joshua Yoon
 
PPTX
Springboot2 postgresql-jpa-hibernate-crud-example with test
HyukSun Kwon
 
PPTX
Spring data jpa are used to develop spring applications
michaelaaron25322
 
DOC
Integration Of Springs Framework In Hibernates
Sunkara Prakash
 
DOC
Integration Of Springs Framework In Hibernates
Sunkara Prakash
 
PDF
Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010
Arun Gupta
 
PPTX
SpringBootCompleteBootcamp.pptx
SUFYAN SATTAR
 
PDF
Struts2 - 101
Munish Gupta
 
PDF
How to configure with Spring an api not based on Spring
Jose María Arranz
 
PPTX
Springboot2 postgresql-jpa-hibernate-crud-example
HyukSun Kwon
 
PDF
Hibernate.pdf
SaadAnsari73
 
PPTX
Dost.jar and fo.jar
Suite Solutions
 
PPT
Ibm
techbed
 
PPTX
MyBatis
Roman Dovgan
 
ODP
Annotation-Based Spring Portlet MVC
John Lewis
 
PPTX
Spring boot for buidling microservices
Nilanjan Roy
 
Sel study notes
Lalit Singh
 
Introduction to Datastore
Software Park Thailand
 
Spring Boot Tutorial Part 2 (JPA&Hibernate) .pdf
abdelr7man3mad2004
 
Java Web Programming on Google Cloud Platform [2/3] : Datastore
IMC Institute
 
Data access
Joshua Yoon
 
Springboot2 postgresql-jpa-hibernate-crud-example with test
HyukSun Kwon
 
Spring data jpa are used to develop spring applications
michaelaaron25322
 
Integration Of Springs Framework In Hibernates
Sunkara Prakash
 
Integration Of Springs Framework In Hibernates
Sunkara Prakash
 
Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010
Arun Gupta
 
SpringBootCompleteBootcamp.pptx
SUFYAN SATTAR
 
Struts2 - 101
Munish Gupta
 
How to configure with Spring an api not based on Spring
Jose María Arranz
 
Springboot2 postgresql-jpa-hibernate-crud-example
HyukSun Kwon
 
Hibernate.pdf
SaadAnsari73
 
Dost.jar and fo.jar
Suite Solutions
 
Ibm
techbed
 
MyBatis
Roman Dovgan
 
Annotation-Based Spring Portlet MVC
John Lewis
 
Spring boot for buidling microservices
Nilanjan Roy
 
Ad

Recently uploaded (20)

PPTX
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
PDF
The 2025 InfraRed Report - Redpoint Ventures
Razin Mustafiz
 
PDF
What’s my job again? Slides from Mark Simos talk at 2025 Tampa BSides
Mark Simos
 
PDF
AI Agents in the Cloud: The Rise of Agentic Cloud Architecture
Lilly Gracia
 
PPTX
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
PDF
Automating Feature Enrichment and Station Creation in Natural Gas Utility Net...
Safe Software
 
PDF
SIZING YOUR AIR CONDITIONER---A PRACTICAL GUIDE.pdf
Muhammad Rizwan Akram
 
PDF
Go Concurrency Real-World Patterns, Pitfalls, and Playground Battles.pdf
Emily Achieng
 
PPT
Ericsson LTE presentation SEMINAR 2010.ppt
npat3
 
PPTX
Digital Circuits, important subject in CS
contactparinay1
 
PDF
How do you fast track Agentic automation use cases discovery?
DianaGray10
 
PDF
UPDF - AI PDF Editor & Converter Key Features
DealFuel
 
PPTX
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
PDF
UiPath DevConnect 2025: Agentic Automation Community User Group Meeting
DianaGray10
 
PDF
“Squinting Vision Pipelines: Detecting and Correcting Errors in Vision Models...
Edge AI and Vision Alliance
 
PPTX
Designing_the_Future_AI_Driven_Product_Experiences_Across_Devices.pptx
presentifyai
 
PDF
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
PPTX
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
PPTX
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
DOCX
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
The 2025 InfraRed Report - Redpoint Ventures
Razin Mustafiz
 
What’s my job again? Slides from Mark Simos talk at 2025 Tampa BSides
Mark Simos
 
AI Agents in the Cloud: The Rise of Agentic Cloud Architecture
Lilly Gracia
 
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
Automating Feature Enrichment and Station Creation in Natural Gas Utility Net...
Safe Software
 
SIZING YOUR AIR CONDITIONER---A PRACTICAL GUIDE.pdf
Muhammad Rizwan Akram
 
Go Concurrency Real-World Patterns, Pitfalls, and Playground Battles.pdf
Emily Achieng
 
Ericsson LTE presentation SEMINAR 2010.ppt
npat3
 
Digital Circuits, important subject in CS
contactparinay1
 
How do you fast track Agentic automation use cases discovery?
DianaGray10
 
UPDF - AI PDF Editor & Converter Key Features
DealFuel
 
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
UiPath DevConnect 2025: Agentic Automation Community User Group Meeting
DianaGray10
 
“Squinting Vision Pipelines: Detecting and Correcting Errors in Vision Models...
Edge AI and Vision Alliance
 
Designing_the_Future_AI_Driven_Product_Experiences_Across_Devices.pptx
presentifyai
 
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
Ad

Configuring jpa in a Spring application

  • 1. How to configure JPA/Hibernate for a Spring application This is a reference/document for developers to understand how JPA/Hibernate is configured for a Spring application. Jayasree Perilakkalam
  • 2. Introduction • This is a reference/document that covers how to configure JPA/Hibernate in a Spring application • In this reference documentation, Maven has been used for dependency management. • Any questions/suggestions/comments are welcome via the comments section below.
  • 3. Maven Dependency Configuration • Add the following in pom.xml file <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>5.4.4.Final</version> </dependency> <!-- https://mvnrepository.com/artifact/org.hibernate.javax.persistence/hibernate-jpa-2.1-api - -> <dependency> <groupId>org.hibernate.javax.persistence</groupId> <artifactId>hibernate-jpa-2.1-api</artifactId> <version>1.0.2.Final</version> </dependency>
  • 4. Annotations used • @Repository - This annotation acts as a marker for a class that fulfills the role/stereotype of a repository (DAO layer). - This is a Spring stereotype annotation and is a specialized @Component annotation. It has @Component annotation within it and thus enables auto discovery of the Spring bean. - Additional to indicating that it is an annotation based configuration, it provides automatic exception translation in the persistence layer when used with the following in the Spring’s application context. @Bean public PersistenceExceptionTranslationPostProcessor exceptionTranslation(){ return new PersistenceExceptionTranslationPostProcessor(); } - Spring Data JPA repository layer(interfaces) are annotated with @Repository
  • 5. Annotations used • @EnableTransactionManagement - This is used in a @Configuration class to enable transactional support. • @Transactional - After the transaction is configured (steps provided in the next couple of slides), this annotation can be added at the class level or the method level to achieve transaction management. Further configuration via the following properties is possible: - propogation Type - isolation Level - Timeout of the operation in @Transactional in seconds - readOnly flag - the Rollback rules - Only public methods can be annotated with @Transactional. The methods with other visibilities will silently ignore this annotation. - Spring creates proxies for all the classes annotated with @Transactional (either at the class level or the method level). The proxy allows Spring to add transactional logic before and after running the method, etc.
  • 6. Understanding EntityManagerFactory • EntityManagerFactory facilitates instantiation of EntityManager instances • EntityManagerFactory is constructed for a specific database and it provides an efficient way to construct multiple EntityManager instances for that database. • EntityManager is a Java interface (part of JPA) and is responsible for starting the particular transaction (EntityTransaction) and managing the persistence operations on entities/objects. EntityTransaction has a one to one relationship with EntityManager. Entity is the persistence objects (stores as records in the database).
  • 7. Configure EntityManagerFactory @Bean public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean() { LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); em.setDataSource(dataSource()); em.setPackagesToScan(new String[] { "com.example.entity" }); // --- package where entity classes exist JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); em.setJpaVendorAdapter(vendorAdapter); em.setJpaProperties(additionalProperties()); return em; } // ...
  • 8. Understanding Spring Framework’s PlatformTransactionManager • PlatformTransactionManager provides transaction abstraction/transaction strategy. • PlatformTransactionManager is a service provider interface(SPI). • JpaTransactionManager (Spring Framework) is an implementation of PlatFormTransactionManager for a single JPA EntityManagerFactory. It binds a JPA EntityManager from the specified factory to the thread, allowing only one-thread bound EntityManager per factory.
  • 9. Configure TransactionManager @Bean public PlatformTransactionManager transactionManager(){ JpaTransactionManager transactionManager = new JpaTransactionManager(); transactionManager.setEntityManagerFactory( entityManagerFactoryBean().getObject() ); return transactionManager; }
  • 10. JNDI DataSource Lookup • Retrieve DataSource from Tomcat Application Server’s context.xml file @Bean public DataSource dataSource() { JndiDataSourceLookup aJndiDataSourceLookup = new JndiDataSourceLookup(); aJndiDataSourceLookup.setResourceRef(true); DataSource aDataSource = aJndiDataSourceLookup.getDataSource(“java:comp/env/jdbc/myoracle”) return aDataSource; } • Configure JNDI Datasource in Tomcat by adding a declaration of the resource in the context.xml file. A sample is as follows: <Resource name="jdbc/myoracle" auth="Container" type="javax.sql.DataSource" driverClassName="oracle.jdbc.OracleDriver" url="jdbc:oracle:thin:@127.0.0.1:1521:mysid" username="scott" password="tiger" maxTotal="20" maxIdle="10" maxWaitMillis="-1"/>
  • 11. Additional Hibernate properties set up private Properties additionalProperties() { Properties properties = new Properties(); …. …. return properties; } Note: PropertiesLoaderUtils (Spring Framework) can be used to load properties from a file.
  • 12. A sample configuration file @Configuration @EnableTransactionManagement @EnableJpaRepositories(basePackages= “com.example.repository”) //  [will scan the package specified here for Spring Data repositories. So this is a Spring Data annotation/configuration ] public class PersistExampleConfig { @Bean public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean() { …. } @Bean public PlatformTransactionManager transactionManager(){ … } Contd…
  • 13. A sample configuration file Contd … @Bean public PersistenceExceptionTranslationPostProcessor exceptionTranslation(){ … } @Bean public DataSource dataSource() { …. } private Properties additionalProperties() { … } }
  • 14. JPA Annotations • Following are some important JPA annotations (for object relational mapping i.e. ORM) - @Entity - @Table - @Id - @Column - @JoinColumn - @ManytoOne Note: I will cover JPA annotations in detail in a separate presentation.
  • 15. Conclusion • We can use @EnableJpaAuditing to enable auditing. This is a Spring Data annotation to enable auditing. I will cover this in a separate presentation. • This is a reference/document to understand Hibernate/JPA configuration in a Spring application • This will help developers to build transactional applications faster. Thank you