With more than 15 years of leading custom software development
projects involving Spring, Joris has gained a lot of real-world
experience, and this call is about sharing and helping the
community.
Enjoy.
Partner – Jmix Haulmont – NPI EA (cat= Architecture)
Building or modernizing a Java enterprise web app has always
been a long process, historically. Not even remotely quick.
That's the main goal of Jmix is to make the process quick
without losing flexibility - with the open-source RAD platform
enabling fast development of business applications.
Critically, it has very minimal impact on your server's
performance, with most of the profiling work done separately - so
it needs no server changes, agents or separate services.
Simply put, a single Java or Kotlin developer can now quickly
implement an entire modular feature, from DB schema, data model,
fine-grained access control, business logic, BPM, all the way to
the UI.
Jmix supports both developer experiences – visual tools and
coding, and a host of super useful plugins as well:
Slow MySQL query performance is all too common. Of course
it is. A good way to go is, naturally, a dedicated profiler that
actually understands the ins and outs of MySQL.
The Jet Profiler was built for MySQL only, so it can do
things like real-time query performance, focus on most used tables
or most frequent queries, quickly identify performance issues and
basically help you optimize your queries.
Critically, it has very minimal impact on your server's
performance, with most of the profiling work done separately - so
it needs no server changes, agents or separate services.
Basically, you install the desktop application, connect to your MySQL
server, hit the record button, and you'll have results
within minutes:
The Kubernetes ecosystem is huge and quite complex, so
it’s easy to forget about costs when trying out all of the exciting
tools.
To avoid overspending on your Kubernetes cluster, definitely
have a look at the free K8s cost monitoring tool from the
automation platform CAST AI. You can view your costs in real time,
allocate them, calculate burn rates for projects, spot anomalies or
spikes, and get insightful reports you can share with your
team.
Connect your cluster and start monitoring your K8s costs
right away:
This tutorial shows how to set up Spring with JPA, using Hibernate as a persistence provider.
For a step-by-step introduction to setting up the Spring context using Java-based configuration and the basic Maven pom for the project, see this article.
We'll start by setting up JPA in a Spring Boot project. Then we'll look into the full configuration we need if we have a standard Spring project.
Here is a video on setting up Hibernate 4 with Spring 4 (we recommend watching it in full 1080p):
2. JPA in Spring Boot
The Spring Boot project is intended to make creating Spring applications much faster and easier. This is done with the use of starters and auto-configuration for various Spring functionalities, JPA among them.
The spring-boot-starter contains the necessary auto-configuration for Spring JPA. Also, the spring-boot-starter-jpa project references all the necessary dependencies such as hibernate-core.
2.2. Configuration
Spring Boot configures Hibernate as the default JPA provider, so it's no longer necessary to define the entityManagerFactory bean unless we want to customize it.
Spring Boot can also auto-configure the dataSource bean, depending on the database we're using. In the case of an in-memory database of type H2, HSQLDB and Apache Derby, Boot automatically configures the DataSource if the corresponding database dependency is present on the classpath.
For example, if we want to use an in-memory H2 database in a Spring Boot JPA application, we only need to add the h2 dependency to the pom.xml file:
Spring Boot will automatically configure a data source based on these properties.
Also in Spring Boot 1, the default connection pool was Tomcat, but it has been changed to HikariCP with Spring Boot 2.
We have more examples of configuring JPA in Spring Boot in the GitHub project.
As we can see, the basic JPA configuration is fairly simple if we're using Spring Boot.
However, if we have a standard Spring project, we need more explicit configuration, using either Java or XML. That's what we'll focus on in the next sections.
3. The JPA Spring Configuration With Java in a Non-Boot Project
To use JPA in a Spring project, we need to set up the EntityManager.
This is the main part of the configuration, and we can do it via a Spring factory bean. This can be either the simpler LocalEntityManagerFactoryBean or the more flexible LocalContainerEntityManagerFactoryBean.
Let's see how we can use the latter option:
@Configuration
@EnableTransactionManagement
public class PersistenceJPAConfig{
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean em
= new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource());
em.setPackagesToScan(new String[] { "com.baeldung.persistence.model" });
JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(vendorAdapter);
em.setJpaProperties(additionalProperties());
return em;
}
// ...
}
We also need to explicitly define the DataSource bean we've used above:
@Bean
public DataSource dataSource(){
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/spring_jpa");
dataSource.setUsername( "tutorialuser" );
dataSource.setPassword( "tutorialmy5ql" );
return dataSource;
}
The final part of the configuration is the additional Hibernate properties and the TransactionManager and exceptionTranslation beans:
@Bean
public PlatformTransactionManager transactionManager() {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
return transactionManager;
}
@Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation(){
return new PersistenceExceptionTranslationPostProcessor();
}
Properties additionalProperties() {
Properties properties = new Properties();
properties.setProperty("hibernate.hbm2ddl.auto", "create-drop");
properties.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");
return properties;
}
4. JPA Spring Configuration With XML
Next, let's see the same Spring configuration with XML:
There's a relatively small difference between the XML and the new Java-based configuration. Namely, in XML, a reference to another bean can point to either the bean or a bean factory for that bean.
But in Java, since the types are different, the compiler doesn't allow it, and so the EntityManagerFactory is first retrieved from its bean factory and then passed to the transaction manager:
Usually, JPA defines a persistence unit through the META-INF/persistence.xml file. Starting with Spring 3.1, the persistence.xml is no longer necessary. The LocalContainerEntityManagerFactoryBean now supports a packagesToScan property where the packages to scan for @Entity classes can be specified.
This file was the last piece of XML we need to remove. We can now set up JPA fully with no XML.
We would usually specify JPA properties in the persistence.xml file.
Alternatively, we can add the properties directly to the entity manager factory bean:
As a side note, if Hibernate is the persistence provider, this would be the way to specify Hibernate-specific properties as well.
6. The Maven Configuration
In addition to the Spring Core and persistence dependencies — shown in detail in the Spring with Maven tutorial — we also need to define JPA and Hibernate in the project as well as a MySQL connector:
Note that the MySQL dependency is included here as an example. We need a driver to configure the data source, but any Hibernate-supported database will do.
7. Conclusion
This tutorial illustrated how to configure JPA with Hibernate in Spring in both a Spring Boot and a standard Spring application.
As always, the code presented in this article is available over on GitHub.
Course – LSD (cat=Persistence)
Get started with Spring Data JPA through the reference Learn Spring Data JPA course: