Spring Data JPA example

In this post, we are going to see about Spring data JPA.
Spring data JPA provides jpaTemplate to integrate Spring and JPA.

Why Spring data JPA:

It is quite cumbersome to implement data access layer now a day. You need to write too much boiler plate code to even execute simple queries and you have to write too much code before and after executing queries. Spring data JPA provides APIs which is quite abstract and you just need to write repository interface  and Spring data JPA will provide implementation automatically. You can also declare some custom find methods (findCountryByName) and spring will provide implementation for it.

Download source code:

Lets understand more with the help of example:
Create Country table in mysql database with following code:

We will you use Country table for querying and updating values in database.
Step 1:
Create a simple maven java project as “SpringDataJPAHibernateExample”.
Step 2:
Include Spring data, hibernate and mysql dependency in pom.xml.

Step 3:Lets create our bean class Country.java

Step 4:
Create a repository interface named CountryRepository.java
You don’t need to provide implementation of it, Spring JPA will provide it automatically.
Step 5:
Create applicationcontext.xml as below
Configure datasource based on your connections details.
entityManagerFactory will have reference to dataSource and jpaVendorAdapter.
Step 6:
Create Main class named SpringApplicationMainBean.java as below
As you can see, we have used autowire annotation to inject CountryRepository in above class. Spring automatically provides implementation for some common methods such as save, delete, findAll etc.
When you run above program, you will get below output:

Was this post helpful?

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *