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