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

PDF
JPA 2.1 performance tuning tips
PPTX
Jpa 2.1 Application Development
PPS
Java Hibernate Programming with Architecture Diagram and Example
PDF
Lecture 9 - Java Persistence, JPA 2
ODP
JPA Best Practices
PDF
Lecture 5 JSTL, custom tags, maven
PPTX
Introduction to JPA (JPA version 2.0)
PDF
Jsp standard tag_library
JPA 2.1 performance tuning tips
Jpa 2.1 Application Development
Java Hibernate Programming with Architecture Diagram and Example
Lecture 9 - Java Persistence, JPA 2
JPA Best Practices
Lecture 5 JSTL, custom tags, maven
Introduction to JPA (JPA version 2.0)
Jsp standard tag_library

What's hot (20)

PPT
Hibernate architecture
PPT
jpa-hibernate-presentation
PPS
Jdbc api
PPTX
Spring & hibernate
PPTX
Introduction to JPA Framework
PPTX
jsp MySQL database connectivity
PPTX
Hibernate ppt
PPTX
Advance java session 5
PPTX
Hibernate in Action
DOC
Hibernate tutorial for beginners
PPT
Entity Persistence with JPA
PPTX
Introduction to jQuery
PDF
Java persistence api 2.1
PPTX
Hibernate
PPTX
Java database connectivity
ODP
Hibernate complete Training
DOC
24 collections framework interview questions
PPT
Hibernate presentation
PPTX
Hibernate Basic Concepts - Presentation
PDF
Lecture 3: Servlets - Session Management
Hibernate architecture
jpa-hibernate-presentation
Jdbc api
Spring & hibernate
Introduction to JPA Framework
jsp MySQL database connectivity
Hibernate ppt
Advance java session 5
Hibernate in Action
Hibernate tutorial for beginners
Entity Persistence with JPA
Introduction to jQuery
Java persistence api 2.1
Hibernate
Java database connectivity
Hibernate complete Training
24 collections framework interview questions
Hibernate presentation
Hibernate Basic Concepts - Presentation
Lecture 3: Servlets - Session Management
Ad

Similar to Configuring jpa in a Spring application (20)

PDF
Spring Data JPA
DOCX
Ecom lec4 fall16_jpa
PDF
Spring db-access mod03
PPTX
Hibernate_ORM_JPA Hibernate_ORM_JPA.pptx
ODP
Jpa buenas practicas
DOC
Integration Of Springs Framework In Hibernates
DOC
Integration Of Springs Framework In Hibernates
PPT
Hibernate
PPTX
Hibernate example1
PPT
02 Hibernate Introduction
KEY
Multi Client Development with Spring
PPT
Basic Hibernate Final
PDF
Spring Boot Tutorial Part 2 (JPA&Hibernate) .pdf
PDF
Java Configuration Deep Dive with Spring
PDF
Leverage Hibernate and Spring Features Together
PPTX
Spring jdbc dao
ODP
Hibernate Developer Reference
PPT
PPTX
Module-3 for career and JFSD ppt for study.pptx
PPT
Patni Hibernate
Spring Data JPA
Ecom lec4 fall16_jpa
Spring db-access mod03
Hibernate_ORM_JPA Hibernate_ORM_JPA.pptx
Jpa buenas practicas
Integration Of Springs Framework In Hibernates
Integration Of Springs Framework In Hibernates
Hibernate
Hibernate example1
02 Hibernate Introduction
Multi Client Development with Spring
Basic Hibernate Final
Spring Boot Tutorial Part 2 (JPA&Hibernate) .pdf
Java Configuration Deep Dive with Spring
Leverage Hibernate and Spring Features Together
Spring jdbc dao
Hibernate Developer Reference
Module-3 for career and JFSD ppt for study.pptx
Patni Hibernate
Ad

Recently uploaded (20)

PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
KodekX | Application Modernization Development
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
Approach and Philosophy of On baking technology
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
Electronic commerce courselecture one. Pdf
PPTX
sap open course for s4hana steps from ECC to s4
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
cuic standard and advanced reporting.pdf
PDF
Review of recent advances in non-invasive hemoglobin estimation
PPTX
Spectroscopy.pptx food analysis technology
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PPTX
Programs and apps: productivity, graphics, security and other tools
Mobile App Security Testing_ A Comprehensive Guide.pdf
KodekX | Application Modernization Development
Encapsulation_ Review paper, used for researhc scholars
Network Security Unit 5.pdf for BCA BBA.
Reach Out and Touch Someone: Haptics and Empathic Computing
Approach and Philosophy of On baking technology
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
20250228 LYD VKU AI Blended-Learning.pptx
Electronic commerce courselecture one. Pdf
sap open course for s4hana steps from ECC to s4
Understanding_Digital_Forensics_Presentation.pptx
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Per capita expenditure prediction using model stacking based on satellite ima...
Unlocking AI with Model Context Protocol (MCP)
cuic standard and advanced reporting.pdf
Review of recent advances in non-invasive hemoglobin estimation
Spectroscopy.pptx food analysis technology
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Programs and apps: productivity, graphics, security and other tools

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