SpringMVC Hibernate CRUD Tutorial using Eclipse

I am going to create today a complete End-to-End SpringMVC 3, Hibernate 3 CRUD tutorial which uses MySQL as a database to store records. This will be a simple Bookstore application where user can Create, Update, View of Delete book records. We will use Hibernate 3 as an ORM tool with Spring MVC as a MVC Framework.

In this tutorial you will learn how we integrate SpringMVC with Hibernate using JPA annotations and I will also going to use Spring annotation configuration for Controller, Service and Repository annotations. The main advantage of using @Repository or @Service over @Component is that it’s easy to write an AOP pointcut that targets, for instance, all classes annotated with @Repository.

Upon completion of this tutorial the Application will look like following screenshot.

Lets Start

First of all, We need a SQL Table to save our Books details in RDBMS. You can create this table by the help of Hibernate also but its good to follow Bottom-Up approach to create an Application. Following SQL used to create a Books table in MySQL database.

1

2

3

4

5

6

7

8

CREATE TABLE IFNOTEXISTS books(

id int(10)NOTNULLauto_increment,

book_name varchar(100)NOTNULL,

author varchar(100)NOTNULL,

price int(10)NOTNULL,

qty int(10)NOTNULL,

PRIMARY KEY(id)

);

Hibernate Entity Class: Book

The @Entity annotation is used to mark this class as an Entity bean. So the class should atleast have a package scope no-argument constructor.

The @Table annotation is used to specify the table to persist the data. The name attribute refers to the table name. If @Table annotation is not specified then Hibernate will by default use the class name as the table name.

The @Id annotation is used to specify the identifier property of the entity bean. The placement of the @Id annotation determines the default access strategy that Hibernate will use for the mapping. If the @Id annotation is placed over the field, then filed access will be used. Instead if it placed over the getter method of that field, then property access will be used. Here we use property access.

The @GeneratedValue annotation is used to specify the primary key generation strategy to use. If the strategy is not specified by default AUTO will be used.

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

59

packageorg.techzoo.springmvc.form;

import javax.persistence.Column;

import javax.persistence.Entity;

import javax.persistence.GeneratedValue;

import javax.persistence.Id;

import javax.persistence.Table;

@Entity

@Table(name="BOOKS",schema="TEST")

publicclassBook{

@Id

@Column(name="ID")

@GeneratedValue

privateIntegerid;

@Column(name="BOOK_NAME")

privateStringbookName;

@Column(name="AUTHOR")

privateStringauthor;

@Column(name="PRICE")

privateintprice;

@Column(name="QTY")

privateintquantity;

publicIntegergetId()

{returnid;}

publicStringgetBookName()

{returnbookName;}

publicStringgetAuthor()

{returnauthor;}

publicintgetPrice()

{returnprice;}

publicintgetQuantity()

{returnquantity;}

publicvoidsetId(Integerid)

{this.id=id;}

publicvoidsetBookName(StringbookName)

{this.bookName=bookName;}

publicvoidsetAuthor(Stringauthor)

{this.author=author;}

publicvoidsetPrice(intprice)

{this.price=price;}

publicvoidsetQuantity(intquantity)

{this.quantity=quantity;}

}

Data Access Layer

Data access layer of our application consist of one BookDoa Interface and its implementation BookDaoImpl class. The BookDaoImpl class has a @Repository annotation which used to enable this class to eligible for persistence exception translation.

Service layer also consist of one Service interface BookService and its implementation class BookServiceImpl.java. We have annotated BookServiceImpl class with @Service annotation.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

packageorg.techzoo.springmvc.service;

import java.util.List;

import org.techzoo.springmvc.form.Book;

publicinterfaceBookService{

publicvoidaddBook(Book book);

publicvoidupdateBook(Book book);

publicBook getBookById(IntegerbookId);

publicList<Book>listBooks();

publicvoidremoveBook(Integerid);

}

BookServiceImpl.java class…

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

packageorg.techzoo.springmvc.service;

import java.util.List;

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

import org.springframework.stereotype.Service;

import org.springframework.transaction.annotation.Transactional;

import org.techzoo.springmvc.dao.BookDao;

import org.techzoo.springmvc.form.Book;

@Service

publicclassBookServiceImplimplementsBookService{

@Autowired

privateBookDao bookDao;

@Transactional

publicvoidaddBook(Book book){

bookDao.addBook(book);

}

@Transactional

publicvoidremoveBook(Integerid){

bookDao.removeBook(id);

}

@Transactional

publicList<Book>listBooks(){

returnbookDao.listBooks();

}

@Transactional

publicvoidupdateBook(Book book){

bookDao.updateBook(book);

}

@Transactional

publicBook getBookById(IntegerbookId){

returnbookDao.getBookById(bookId);

}

}

Book Controller

Now create a BookController which will have all the method we need for our CRUD operations. We need to wire the bookService for this controller using @Autowired annotation.

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

59

60

61

packageorg.techzoo.springmvc.controller;

import java.util.Map;

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

import org.springframework.stereotype.Controller;

import org.springframework.validation.BindingResult;

import org.springframework.web.bind.annotation.ModelAttribute;

import org.springframework.web.bind.annotation.PathVariable;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;

import org.techzoo.springmvc.form.Book;

import org.techzoo.springmvc.service.BookService;

@Controller

publicclassBookController{

@Autowired

privateBookService bookService;

@RequestMapping("/index")

publicStringlistBooks(Map<String,Object>map){

map.put("book",newBook());

map.put("bookList",bookService.listBooks());

return"book";

}

@RequestMapping(

value="/book/add",

method=RequestMethod.POST

)

publicStringaddBook(@ModelAttribute("book")

Book book,BindingResult result)

{

if(null==book.getId()){

bookService.addBook(book);

}

else{

bookService.updateBook(book);

}

return"redirect:/index";

}

@RequestMapping("/delete/{bookId}")

publicStringdeleteBook(

@PathVariable("bookId")IntegerbookId)

{

bookService.removeBook(bookId);

return"redirect:/index";

}

@RequestMapping("/edit/{bookId}")

publicStringeditBook(

@PathVariable("bookId")IntegerbookId,

Map<String,Object>map)

{

map.put("book",bookService.getBookById(bookId));

map.put("bookList",bookService.listBooks());

return"book";

}

}

SpringMVC Configuration

Now we are all set with our java changes and we need to add spring relate configuration in xml files. First we add DispatcherServlet reference in web.xml file. Following xml tags will add a DispatcherServlet reference to web.xml file.

1

2

3

4

5

6

7

8

9

10

11

12

<servlet>

<servlet-name>spring</servlet-name>

<servlet-class>

org.springframework.web.servlet.DispatcherServlet

</servlet-class>

<load-on-startup>1</load-on-startup>

</servlet>

<servlet-mapping>

<servlet-name>spring</servlet-name>

<url-pattern>/</url-pattern>

</servlet-mapping>

Now create a jdbc.properties file which is used to set Database related properties into it. We can add those properties directly into spring xml file but it’s good to create a separate file and have all details of DB into it.

1

2

3

4

5

jdbc.driverClassName=com.mysql.jdbc.Driver

jdbc.dialect=org.hibernate.dialect.MySQLDialect

jdbc.databaseurl=jdbc:mysql://localhost:3306/test

jdbc.username=root

jdbc.password=

Hibernate Configuration

We have created a Hinerbate Entity Book which is annotation base Entity. The benefit of creating an annotation based Entity class is We don’t need to create a .hbm.xml file for that entity but we need to create hibernate.cfg.xml file for Hibernate related configuration. Following XML shows the mininum Hibernate configuration File.

1

2

3

4

5

6

7

8

9

10

11

<?xml version='1.0'encoding='utf-8'?>

<!DOCTYPE hibernate-configuration PUBLIC

"-//Hibernate/Hibernate Configuration DTD//EN"

"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

<session-factory>

<mapping class="org.techzoo.springmvc.form.Book"/>

</session-factory>

</hibernate-configuration>

Spring Configuration

Now we need to add spring-servler.xml file which contain all beans and others MVC, Transaction related Tags. XML file is minimal and self-explanatory.

Now last but not the least, creating view to show our Book Add Form. I have also created a Table grid which show the List of all available Books after Book Entry form. You can click on Book Name and it will show the details for the Book. Further you can edit the details and Save it to Update the Changes.

About the Author

I Love Coding, Analyzing, Designing and doing it the right way. I am obsessed about learn anything new daily and sharing what I have learn each Day. This Blog is journey of my Zeal, going through step by step to the mountain of desire to become prefect.
GoogleWanna Hire me ?