SlideShare une entreprise Scribd 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

Contenu connexe

Tendances

Tendances (20)

Hibernate architecture
Hibernate architectureHibernate architecture
Hibernate architecture
 
jpa-hibernate-presentation
jpa-hibernate-presentationjpa-hibernate-presentation
jpa-hibernate-presentation
 
Jdbc api
Jdbc apiJdbc api
Jdbc api
 
Spring & hibernate
Spring & hibernateSpring & hibernate
Spring & hibernate
 
Introduction to JPA Framework
Introduction to JPA FrameworkIntroduction to JPA Framework
Introduction to JPA Framework
 
jsp MySQL database connectivity
jsp MySQL database connectivityjsp MySQL database connectivity
jsp MySQL database connectivity
 
Hibernate ppt
Hibernate pptHibernate ppt
Hibernate ppt
 
Advance java session 5
Advance java session 5Advance java session 5
Advance java session 5
 
Hibernate in Action
Hibernate in ActionHibernate in Action
Hibernate in Action
 
Hibernate tutorial for beginners
Hibernate tutorial for beginnersHibernate tutorial for beginners
Hibernate tutorial for beginners
 
Entity Persistence with JPA
Entity Persistence with JPAEntity Persistence with JPA
Entity Persistence with JPA
 
Introduction to jQuery
Introduction to jQueryIntroduction to jQuery
Introduction to jQuery
 
Java persistence api 2.1
Java persistence api 2.1Java persistence api 2.1
Java persistence api 2.1
 
Hibernate
HibernateHibernate
Hibernate
 
Java database connectivity
Java database connectivityJava database connectivity
Java database connectivity
 
Hibernate complete Training
Hibernate complete TrainingHibernate complete Training
Hibernate complete Training
 
24 collections framework interview questions
24 collections framework interview questions24 collections framework interview questions
24 collections framework interview questions
 
Hibernate presentation
Hibernate presentationHibernate presentation
Hibernate presentation
 
Hibernate Basic Concepts - Presentation
Hibernate Basic Concepts - PresentationHibernate Basic Concepts - Presentation
Hibernate Basic Concepts - Presentation
 
Lecture 3: Servlets - Session Management
Lecture 3:  Servlets - Session ManagementLecture 3:  Servlets - Session Management
Lecture 3: Servlets - Session Management
 

Similaire à Configuring jpa in a Spring application

Java Web Programming on Google Cloud Platform [2/3] : Datastore
Java Web Programming on Google Cloud Platform [2/3] : DatastoreJava Web Programming on Google Cloud Platform [2/3] : Datastore
Java Web Programming on Google Cloud Platform [2/3] : DatastoreIMC Institute
 
Springboot2 postgresql-jpa-hibernate-crud-example with test
Springboot2 postgresql-jpa-hibernate-crud-example with testSpringboot2 postgresql-jpa-hibernate-crud-example with test
Springboot2 postgresql-jpa-hibernate-crud-example with testHyukSun Kwon
 
Spring data jpa are used to develop spring applications
Spring data jpa are used to develop spring applicationsSpring data jpa are used to develop spring applications
Spring data jpa are used to develop spring applicationsmichaelaaron25322
 
Integration Of Springs Framework In Hibernates
Integration Of Springs Framework In HibernatesIntegration Of Springs Framework In Hibernates
Integration Of Springs Framework In HibernatesSunkara Prakash
 
Integration Of Springs Framework In Hibernates
Integration Of Springs Framework In HibernatesIntegration Of Springs Framework In Hibernates
Integration Of Springs Framework In HibernatesSunkara Prakash
 
Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010
Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010
Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010Arun Gupta
 
SpringBootCompleteBootcamp.pptx
SpringBootCompleteBootcamp.pptxSpringBootCompleteBootcamp.pptx
SpringBootCompleteBootcamp.pptxSUFYAN SATTAR
 
How to configure with Spring an api not based on Spring
How to configure with Spring an api not based on SpringHow to configure with Spring an api not based on Spring
How to configure with Spring an api not based on SpringJose María Arranz
 
Springboot2 postgresql-jpa-hibernate-crud-example
Springboot2 postgresql-jpa-hibernate-crud-exampleSpringboot2 postgresql-jpa-hibernate-crud-example
Springboot2 postgresql-jpa-hibernate-crud-exampleHyukSun Kwon
 
Annotation-Based Spring Portlet MVC
Annotation-Based Spring Portlet MVCAnnotation-Based Spring Portlet MVC
Annotation-Based Spring Portlet MVCJohn Lewis
 
Spring boot for buidling microservices
Spring boot for buidling microservicesSpring boot for buidling microservices
Spring boot for buidling microservicesNilanjan Roy
 
Web container and Apache Tomcat
Web container and Apache TomcatWeb container and Apache Tomcat
Web container and Apache TomcatAuwal Amshi
 

Similaire à Configuring jpa in a Spring application (20)

Sel study notes
Sel study notesSel study notes
Sel study notes
 
Introduction to Datastore
Introduction to DatastoreIntroduction to Datastore
Introduction to Datastore
 
Java Web Programming on Google Cloud Platform [2/3] : Datastore
Java Web Programming on Google Cloud Platform [2/3] : DatastoreJava Web Programming on Google Cloud Platform [2/3] : Datastore
Java Web Programming on Google Cloud Platform [2/3] : Datastore
 
Data access
Data accessData access
Data access
 
Springboot2 postgresql-jpa-hibernate-crud-example with test
Springboot2 postgresql-jpa-hibernate-crud-example with testSpringboot2 postgresql-jpa-hibernate-crud-example with test
Springboot2 postgresql-jpa-hibernate-crud-example with test
 
Spring data jpa are used to develop spring applications
Spring data jpa are used to develop spring applicationsSpring data jpa are used to develop spring applications
Spring data jpa are used to develop spring applications
 
Integration Of Springs Framework In Hibernates
Integration Of Springs Framework In HibernatesIntegration Of Springs Framework In Hibernates
Integration Of Springs Framework In Hibernates
 
Integration Of Springs Framework In Hibernates
Integration Of Springs Framework In HibernatesIntegration Of Springs Framework In Hibernates
Integration Of Springs Framework In Hibernates
 
Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010
Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010
Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010
 
SpringBootCompleteBootcamp.pptx
SpringBootCompleteBootcamp.pptxSpringBootCompleteBootcamp.pptx
SpringBootCompleteBootcamp.pptx
 
Struts2 - 101
Struts2 - 101Struts2 - 101
Struts2 - 101
 
How to configure with Spring an api not based on Spring
How to configure with Spring an api not based on SpringHow to configure with Spring an api not based on Spring
How to configure with Spring an api not based on Spring
 
Springboot2 postgresql-jpa-hibernate-crud-example
Springboot2 postgresql-jpa-hibernate-crud-exampleSpringboot2 postgresql-jpa-hibernate-crud-example
Springboot2 postgresql-jpa-hibernate-crud-example
 
Hibernate.pdf
Hibernate.pdfHibernate.pdf
Hibernate.pdf
 
Dost.jar and fo.jar
Dost.jar and fo.jarDost.jar and fo.jar
Dost.jar and fo.jar
 
Ibm
IbmIbm
Ibm
 
MyBatis
MyBatisMyBatis
MyBatis
 
Annotation-Based Spring Portlet MVC
Annotation-Based Spring Portlet MVCAnnotation-Based Spring Portlet MVC
Annotation-Based Spring Portlet MVC
 
Spring boot for buidling microservices
Spring boot for buidling microservicesSpring boot for buidling microservices
Spring boot for buidling microservices
 
Web container and Apache Tomcat
Web container and Apache TomcatWeb container and Apache Tomcat
Web container and Apache Tomcat
 

Dernier

UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3DianaGray10
 
Integrating Telephony Systems with Salesforce: Insights and Considerations, B...
Integrating Telephony Systems with Salesforce: Insights and Considerations, B...Integrating Telephony Systems with Salesforce: Insights and Considerations, B...
Integrating Telephony Systems with Salesforce: Insights and Considerations, B...CzechDreamin
 
Powerful Start- the Key to Project Success, Barbara Laskowska
Powerful Start- the Key to Project Success, Barbara LaskowskaPowerful Start- the Key to Project Success, Barbara Laskowska
Powerful Start- the Key to Project Success, Barbara LaskowskaCzechDreamin
 
Optimizing NoSQL Performance Through Observability
Optimizing NoSQL Performance Through ObservabilityOptimizing NoSQL Performance Through Observability
Optimizing NoSQL Performance Through ObservabilityScyllaDB
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Product School
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfCheryl Hung
 
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...CzechDreamin
 
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo DiehlFuture Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo DiehlPeter Udo Diehl
 
Free and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
Free and Effective: Making Flows Publicly Accessible, Yumi IbrahimzadeFree and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
Free and Effective: Making Flows Publicly Accessible, Yumi IbrahimzadeCzechDreamin
 
ODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User GroupODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User GroupCatarinaPereira64715
 
Custom Approval Process: A New Perspective, Pavel Hrbacek & Anindya Halder
Custom Approval Process: A New Perspective, Pavel Hrbacek & Anindya HalderCustom Approval Process: A New Perspective, Pavel Hrbacek & Anindya Halder
Custom Approval Process: A New Perspective, Pavel Hrbacek & Anindya HalderCzechDreamin
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Product School
 
In-Depth Performance Testing Guide for IT Professionals
In-Depth Performance Testing Guide for IT ProfessionalsIn-Depth Performance Testing Guide for IT Professionals
In-Depth Performance Testing Guide for IT ProfessionalsExpeed Software
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...Product School
 
Demystifying gRPC in .Net by John Staveley
Demystifying gRPC in .Net by John StaveleyDemystifying gRPC in .Net by John Staveley
Demystifying gRPC in .Net by John StaveleyJohn Staveley
 
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)Julian Hyde
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Jeffrey Haguewood
 
UiPath Test Automation using UiPath Test Suite series, part 1
UiPath Test Automation using UiPath Test Suite series, part 1UiPath Test Automation using UiPath Test Suite series, part 1
UiPath Test Automation using UiPath Test Suite series, part 1DianaGray10
 
UiPath Test Automation using UiPath Test Suite series, part 2
UiPath Test Automation using UiPath Test Suite series, part 2UiPath Test Automation using UiPath Test Suite series, part 2
UiPath Test Automation using UiPath Test Suite series, part 2DianaGray10
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualityInflectra
 

Dernier (20)

UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
 
Integrating Telephony Systems with Salesforce: Insights and Considerations, B...
Integrating Telephony Systems with Salesforce: Insights and Considerations, B...Integrating Telephony Systems with Salesforce: Insights and Considerations, B...
Integrating Telephony Systems with Salesforce: Insights and Considerations, B...
 
Powerful Start- the Key to Project Success, Barbara Laskowska
Powerful Start- the Key to Project Success, Barbara LaskowskaPowerful Start- the Key to Project Success, Barbara Laskowska
Powerful Start- the Key to Project Success, Barbara Laskowska
 
Optimizing NoSQL Performance Through Observability
Optimizing NoSQL Performance Through ObservabilityOptimizing NoSQL Performance Through Observability
Optimizing NoSQL Performance Through Observability
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...
 
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo DiehlFuture Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
 
Free and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
Free and Effective: Making Flows Publicly Accessible, Yumi IbrahimzadeFree and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
Free and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
 
ODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User GroupODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User Group
 
Custom Approval Process: A New Perspective, Pavel Hrbacek & Anindya Halder
Custom Approval Process: A New Perspective, Pavel Hrbacek & Anindya HalderCustom Approval Process: A New Perspective, Pavel Hrbacek & Anindya Halder
Custom Approval Process: A New Perspective, Pavel Hrbacek & Anindya Halder
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
 
In-Depth Performance Testing Guide for IT Professionals
In-Depth Performance Testing Guide for IT ProfessionalsIn-Depth Performance Testing Guide for IT Professionals
In-Depth Performance Testing Guide for IT Professionals
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
 
Demystifying gRPC in .Net by John Staveley
Demystifying gRPC in .Net by John StaveleyDemystifying gRPC in .Net by John Staveley
Demystifying gRPC in .Net by John Staveley
 
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
 
UiPath Test Automation using UiPath Test Suite series, part 1
UiPath Test Automation using UiPath Test Suite series, part 1UiPath Test Automation using UiPath Test Suite series, part 1
UiPath Test Automation using UiPath Test Suite series, part 1
 
UiPath Test Automation using UiPath Test Suite series, part 2
UiPath Test Automation using UiPath Test Suite series, part 2UiPath Test Automation using UiPath Test Suite series, part 2
UiPath Test Automation using UiPath Test Suite series, part 2
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
 

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