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

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

What's hot (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
 

Similar to Configuring jpa in a Spring application

Sel study notes
Sel study notesSel study notes
Sel study notes
Lalit Singh
 
Introduction to Datastore
Introduction to DatastoreIntroduction to Datastore
Introduction to Datastore
Software Park Thailand
 
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
IMC Institute
 
Data access
Data accessData access
Data access
Joshua Yoon
 
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
HyukSun 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 applications
michaelaaron25322
 
Integration Of Springs Framework In Hibernates
Integration Of Springs Framework In HibernatesIntegration Of Springs Framework In Hibernates
Integration Of Springs Framework In Hibernates
Sunkara Prakash
 
Integration Of Springs Framework In Hibernates
Integration Of Springs Framework In HibernatesIntegration Of Springs Framework In Hibernates
Integration Of Springs Framework In Hibernates
Sunkara 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 2010
Arun Gupta
 
SpringBootCompleteBootcamp.pptx
SpringBootCompleteBootcamp.pptxSpringBootCompleteBootcamp.pptx
SpringBootCompleteBootcamp.pptx
SUFYAN SATTAR
 
Struts2 - 101
Struts2 - 101Struts2 - 101
Struts2 - 101
Munish Gupta
 
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
Jose 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-example
HyukSun Kwon
 
Hibernate.pdf
Hibernate.pdfHibernate.pdf
Hibernate.pdf
SaadAnsari73
 
Dost.jar and fo.jar
Dost.jar and fo.jarDost.jar and fo.jar
Dost.jar and fo.jar
Suite Solutions
 
Ibm
IbmIbm
Ibm
techbed
 
MyBatis
MyBatisMyBatis
MyBatis
Roman Dovgan
 
Annotation-Based Spring Portlet MVC
Annotation-Based Spring Portlet MVCAnnotation-Based Spring Portlet MVC
Annotation-Based Spring Portlet MVC
John Lewis
 
Spring boot for buidling microservices
Spring boot for buidling microservicesSpring boot for buidling microservices
Spring boot for buidling microservices
Nilanjan Roy
 
Web container and Apache Tomcat
Web container and Apache TomcatWeb container and Apache Tomcat
Web container and Apache Tomcat
Auwal Amshi
 

Similar to 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
 

Recently uploaded

GraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracyGraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracy
Tomaz Bratanic
 
How to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For FlutterHow to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For Flutter
Daiki Mogmet Ito
 
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
Neo4j
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
mikeeftimakis1
 
Building Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and MilvusBuilding Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and Milvus
Zilliz
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
Mind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AIMind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AI
Kumud Singh
 
AI 101: An Introduction to the Basics and Impact of Artificial Intelligence
AI 101: An Introduction to the Basics and Impact of Artificial IntelligenceAI 101: An Introduction to the Basics and Impact of Artificial Intelligence
AI 101: An Introduction to the Basics and Impact of Artificial Intelligence
IndexBug
 
Programming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup SlidesProgramming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup Slides
Zilliz
 
Pushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 daysPushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 days
Adtran
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
Aftab Hussain
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
SOFTTECHHUB
 
GenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizationsGenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizations
kumardaparthi1024
 
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
Neo4j
 
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
SOFTTECHHUB
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
Uni Systems S.M.S.A.
 
HCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAUHCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAU
panagenda
 
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdfUni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems S.M.S.A.
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
Matthew Sinclair
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
Matthew Sinclair
 

Recently uploaded (20)

GraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracyGraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracy
 
How to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For FlutterHow to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For Flutter
 
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
 
Building Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and MilvusBuilding Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and Milvus
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
Mind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AIMind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AI
 
AI 101: An Introduction to the Basics and Impact of Artificial Intelligence
AI 101: An Introduction to the Basics and Impact of Artificial IntelligenceAI 101: An Introduction to the Basics and Impact of Artificial Intelligence
AI 101: An Introduction to the Basics and Impact of Artificial Intelligence
 
Programming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup SlidesProgramming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup Slides
 
Pushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 daysPushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 days
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
 
GenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizationsGenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizations
 
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
 
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
 
HCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAUHCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAU
 
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdfUni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdf
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
 

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