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.

Maven dependencies

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

1

2

3

4

5

6

7

<dependency>

<groupId>com.fasterxml.jackson.core</groupId>

<artifactId>jackson-databind</artifactId>

<version>2.4.1</version>

</dependency>

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.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

packageorg.arpit.java2blog.model;

import javax.persistence.Column;

import javax.persistence.Entity;

import javax.persistence.GeneratedValue;

import javax.persistence.GenerationType;

import javax.persistence.Id;

import javax.persistence.Table;

/*

* This is our model class and it corresponds to Country table in database

*/

@Entity

@Table(name="COUNTRY")

publicclassCountry{

@Id

@Column(name="id")

@GeneratedValue(strategy=GenerationType.IDENTITY)

intid;

@Column(name="countryName")

StringcountryName;

@Column(name="population")

longpopulation;

publicCountry(){

super();

}

publicCountry(inti,StringcountryName,longpopulation){

super();

this.id=i;

this.countryName=countryName;

this.population=population;

}

publicintgetId(){

returnid;

}

publicvoidsetId(intid){

this.id=id;

}

publicStringgetCountryName(){

returncountryName;

}

publicvoidsetCountryName(StringcountryName){

this.countryName=countryName;

}

publiclonggetPopulation(){

returnpopulation;

}

publicvoidsetPopulation(longpopulation){

this.population=population;

}

}

@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:

1

2

3

4

5

6

7

8

9

CREATE TABLE COUNTRY

(

id intPRIMARY KEY NOTNULLAUTO_INCREMENT,

countryName varchar(100)NOTNULL,

population intNOTNULL

)

;

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.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

packageorg.arpit.java2blog.dao;

import java.util.List;

import org.arpit.java2blog.model.Country;

import org.hibernate.Session;

import org.hibernate.SessionFactory;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Repository;

@Repository

publicclassCountryDAO{

@Autowired

privateSessionFactory sessionFactory;

publicvoidsetSessionFactory(SessionFactory sf){

this.sessionFactory=sf;

}

publicList getAllCountries(){

Session session=this.sessionFactory.getCurrentSession();

List countryList=session.createQuery("from Country").list();

returncountryList;

}

publicCountry getCountry(intid){

Session session=this.sessionFactory.getCurrentSession();

Country country=(Country)session.load(Country.class,newInteger(id));

returncountry;

}

publicCountry addCountry(Country country){

Session session=this.sessionFactory.getCurrentSession();

session.persist(country);

returncountry;

}

publicvoidupdateCountry(Country country){

Session session=this.sessionFactory.getCurrentSession();

session.update(country);

}

publicvoiddeleteCountry(intid){

Session session=this.sessionFactory.getCurrentSession();

Countryp=(Country)session.load(Country.class,newInteger(id));

if(null!=p){

session.delete(p);

}

}

}

@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.

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.

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.

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.

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