Configure Spring Data JPA with @EnableJpaRepositories annotation

In the tutorial Overview about Spring Data JPA, I introduced you to Spring Data JPA and how to configure it using XML files. There is another way to configure Spring Data JPA which is to use the annotations it supports such as the @EnableJpaRepositories annotation. How is it in detail? Let’s find out together in this tutorial!

First, I will create a new Maven project as an example:

Spring Data JPA and Hibernate implementation dependencies are as follows:

I will use the MySQL database as an example:

And Project Lombok:

As an example and for simplicity, I define a table in the database containing student information with 2 columns as follows:

The entity of this table:

and Repository class for it:

Now, I will create a new class to configure the application’s database manipulation using Spring Data JPA’s Repository classes with the @EnableJpaRepositories annotation as follows:

Spring when scanning and encountering this @EnableJpaRepositories annotation will automatically initialize the necessary objects so that we can use Spring Data JPA’s Repository.

The basePackages property will define the package in which we have defined the Repositories. There are two other properties of the @EnableJpaRepositories annotation that we need to configure: entityManagerFactoryRef and transactionManagerRef. The values of these properties are the bean names created in the Spring container, for classes of EntityManagerFactory and TransactionManager respectively. The default values of these two properties are entityManagerFactory and transactionManager, respectively.

For EntityManagerFactory, you can use the implementation of class LocalContainerEntityManagerFactoryBean like me as follows:

The setPackagesToScan() method declares the package that will contain the application’s JPA entities. In my example, it is package com.huongdanjava.springdatajpa.entity.

The setDataSource() method will configure the DataSource information to connect to the database, you can declare a DataSource bean with the implementation of the DriverManagerDataSource class as follows:

The database information in the configuration of the DataSource you should get from the properties file. Here, for simplicity, I hardcoded this information.

Bean for TransactionManager, you can declare as follows:

At this point, we have configured Spring Data JPA for our application.

To check the results, I will write a class with the main() method with the following content:

Suppose in the database, I have the following information:

Then the output when running the application will be as follows:

Add Comment