Spring Rest Hibernate example

In previous post, we have already seen Spring Rest crud example . In this post, we will extend same example and integrate it with hibernate and mysql.
We will use following annotations for CRUD operation.

Method
Description
Get
It is used to read resource
Post
It is used to create new resource.
It is not idempotent method
Put
It is generally used to update resource.It is idempotent method
Delete
It is used to delete resource

Idempotent means result of multiple successful request will not change state of resource after initial application
For example :
Delete is idempotent method because when you first time use delete, it will delete the resource (initial application) but after that, all other request will have no result because resource is already deleted.

Post is not idempotent method because when you use post to create resource , it will keep creating resource for each new request, so result of multiple successful request will not be same.

Source code:

Here are steps to create a Spring Restful web services with hibernate integration.

1) Create a dynamic web project using maven in eclipse named “SpringRestHibernateExample”

Maven dependencies

2) We need to add Jackson json utility in the classpath.

Spring will load Jackson2JsonMessageConverter into its application context automatically. Whenever you request resource as json with accept headers=”Accept=application/json”, then Jackson2JsonMessageConverter comes into picture and convert resource to json format.
Now change pom.xml as follows:
pom.xml
4) create a xml file named spring-servlet.xml in /WEB-INF/ folder.
Please change context:component-scan if you want to use different package for spring to search for controller.Please refer to spring mvc hello world example for more understanding.
In Spring-servlet.xml, we have done hibernate configuration.
dataSource bean is used to specify java data source. We need to provide driver, URL , Username and Password.
transactionManager bean is used to configure hibernate transaction manager. hibernate4AnnotatedSessionFactory bean is used to configure FactoryBean that creates a Hibernate SessionFactory. This is the common way to set up a shared Hibernate SessionFactory in a Spring application context, so you can use this SessionFactory to inject in Hibernate data access objects.

Create bean class

4) Create a bean name “Country.java” in org.arpit.java2blog.bean.

@Entity is used for making a persistent pojo class.For this java class,you will have corresponding table in database. @Column is used to map annotated attribute to corresponding column in table. So Create Country table in mysql database with following code:

Create Controller

5) Create a controller named “CountryController.java” in package org.arpit.java2blog.controller

Create DAO class

Create a class CountryDAO.java in package org.arpit.java2blog.dao.  This class will execute hibernate statements while interacting with database.

@Repository is specialised component annotation which is used to create bean at DAO layer. We have use Autowired annotation to inject hibernate SessionFactory into CountryDAO class. We have already configured hibernate SessionFactory object in Spring-Servlet.xml file.

Create Service class

6) Create a class CountryService.java in package org.arpit.java2blog.service
It is service level class. It will call DAO layer class.
@Service is specialised component annotation which is used to create bean at Service layer.
7) It ‘s time to do maven build.

Right click on project -> Run as -> Maven build

Maven build in eclipse
8) Provide goals as clean install (given below) and click on run
Maven build in eclipse

Run the application

9) Right click on project -> run as -> run on server
Select apache tomcat and click on finish
10) We will test this application in  postman , UI based client for testing restful web applications. It is chrome plugin. Launch postman.If you want java based client, then you can also use how to send get or post request in java.

Post method

12) Post method is used to create new resource. Here we are adding new Country India to country list, so you can see we have used new country json in post body.
URL: “http://localhost:8080/SpringRestHibernateExample/addCountry”.

Lets see corresponding entry in Country table in database.

Lets create 3 more countries i.e. china, nepal and USA in similar way.

Put Method

13) Put method is used to update resource. Here will update population of nepal using put method.
We will update country json in body of request.
URL : “http://localhost:8080/SpringRestHibernateExample/updateCountry”

Lets check Nepal’s population in database.

Delete method

14) Delete method is used to delete resource.We will pass id of country which needs to be deleted as PathParam. We are going delete id:3 i.e. Nepal to demonstrate delete method.

URL : “http://localhost:8080/SpringRestHibernateExample/deleteCountry/3”

Lets check entry in database now.

As you can see, we have deleted country with id 3 i.e. Nepal

Project structure:


We are done with Spring Restful web services json CRUD example. If you are still facing any issue, please comment.

If you getting 404 error with above steps, you may need to follow below steps:


1) If you are getting this warning into your Tomcat startup console log, then it can cause the issue
WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property ‘source’ to ‘org.eclipse.jst.j2ee.server: JAXRSJsonCRUDExample’ did not find a matching property.
This particular warning basically means that the element in Tomcat’s server.xml contains an unknown attribute source and that Tomcat doesn’t know what to do with this attribute and therefore will ignore it.
To resolve this in eclipse,
Remove the project from the server from the Server View. Right click on server -> add and remove
then remove project from server configuration.
Then run the project under the same server. Warning should be removed now
Or if warning still remains then
  • Go to server view
  • Double click on your tomcat server. It will open the server configuration.
  • Under server options check ‘Publish module contents to separate XML files’ checkbox.
  • Restart your server. This time your page will come without any issues.
2) Try to update Maven project.
Right click on project ->Maven-> update project
Update Maven project
then

This should solve you issues.

Enti

Was this post helpful?

Comments

    1. Hi Rohit,
      You need to configure mysql and hibernate. I think you have already done it.
      You also need to create a table in database as below and run the application. It should work. Let me know if you are still facing any issues.

      CREATE TABLE COUNTRY
      (
      id int PRIMARY KEY NOT NULL AUTO_INCREMENT,
      countryName varchar(100) NOT NULL,
      population int NOT NULL
      )
      ;

  1. I have implemented the example, I am able to fetch data from database in json format, but other methods like getById, addDetails, Update, delete are not working. Status 500. Please help me to resolve this issue

Leave a Reply

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