SpringMVC + Hibernate CRUD Application

Source: Internet
Author: User

SpringMVC + Hibernate CRUD Application
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@RepositoryOr@ServiceOver@ComponentIs that it's easy to write an AOP pointcut that targets, for instance, all classes annotated@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.

CREATE TABLE IF NOT EXISTS books (  id int(10) NOT NULL auto_increment,  book_name varchar(100) NOT NULL,  author varchar(100) NOT NULL,  price int(10) NOT NULL,  qty int(10) NOT NULL,  PRIMARY KEY  (id));

Hibernate Entity Class: Book

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

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

The@IdAnnotation 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@IdAnnotation 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@GeneratedValueAnnotation is used to specify the primary key generation strategy to use. If the strategy is not specified by default AUTO will be used.

package com.mmc.bean;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")public class Book {@Id@Column(name="ID")@GeneratedValueprivate Integer id;@Column(name="BOOK_NAME")private String bookName;@Column(name="AUTHOR")private String author;@Column(name="PRICE")private int price;@Column(name="QTY")private int quantity;public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getBookName() {return bookName;}public void setBookName(String bookName) {this.bookName = bookName;}public String getAuthor() {return author;}public void setAuthor(String author) {this.author = author;}public int getPrice() {return price;}public void setPrice(int price) {this.price = price;}public int getQuantity() {return quantity;}public void setQuantity(int quantity) {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@RepositoryAnnotation which used to enable this class to eligible for persistence exception translation.

package com.mmc.dao;import java.util.List;import com.mmc.bean.Book;public interface BookDao {public void addBook(Book book);public void updateBook(Book book);public List
 
   listBooks();public Book getBookById(Integer bookId);public void removeBook(Integer id);}
 

BookDaoImpl. java
package com.mmc.dao;import java.util.List;import org.hibernate.Query;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Repository;import com.mmc.bean.Book;@Repositorypublic class BookDaoImpl implements BookDao {@Autowiredprivate SessionFactory sessionFactory;@Overridepublic void addBook(Book book) {sessionFactory.getCurrentSession().save(book);}@Overridepublic void updateBook(Book book) {sessionFactory.getCurrentSession().update(book);}@SuppressWarnings("unchecked")@Overridepublic List
 
   listBooks() {return sessionFactory.getCurrentSession().createQuery("from Book").list();}@Overridepublic Book getBookById(Integer bookId) {Session session = sessionFactory.getCurrentSession();Query query = session.createQuery("from Book b where b.id = :bookId");query.setParameter("bookId", bookId);List
  
    list = query.list();return list.size() > 0 ? (Book)list.get(0) : null;}@Overridepublic void removeBook(Integer id) {Book book = (Book)sessionFactory.getCurrentSession().load(Book.class, id);if(book!=null){sessionFactory.getCurrentSession().delete(book);}}}
  
 

Service Layer

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

Package com. mmc. service;


package com.mmc.service;import java.util.List;import com.mmc.bean.Book;public interface BookService {public void addBook(Book book);public void updateBook(Book book);public Book getBookById(Integer bookId);public List
 
   listBooks();public void removeBook(Integer id);}
 

BookServiceImpl. java
package com.mmc.service;import java.util.List;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;import com.mmc.bean.Book;import com.mmc.dao.BookDao;@Servicepublic class BookServiceImpl implements BookService {@Autowiredprivate BookDao bookDao;@Transactional@Overridepublic void addBook(Book book) {bookDao.addBook(book);}@Transactional@Overridepublic void updateBook(Book book) {bookDao.updateBook(book);}@Transactional@Overridepublic Book getBookById(Integer bookId) {return bookDao.getBookById(bookId);}@Transactional@Overridepublic List
 
   listBooks() {return bookDao.listBooks();}@Transactional@Overridepublic void removeBook(Integer id) {bookDao.removeBook(id);}}
 

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

package com.mmc.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 com.mmc.bean.Book;import com.mmc.service.BookService;@Controllerpublic class BookController {@Autowiredprivate BookService bookService;@RequestMapping("/index")public String bookList(Map
 
   map){map.put("book", new Book());map.put("listBooks", bookService.listBooks());return "book";}@RequestMapping(value="/book/add",method=RequestMethod.POST)public String addBook(@ModelAttribute("book") Book book,BindingResult result){if(null == book.getId()){bookService.addBook(book);} else{bookService.updateBook(book);}return "redirect:/index";}@RequestMapping(value="/edit/{bookId}")public String editBook(@PathVariable("bookId")Integer bookId,Map
  
    map){map.put("book", bookService.getBookById(bookId));map.put("listBooks", bookService.listBooks());return "book";}@RequestMapping(value="/delete/{bookId}")public String deleteBook(@PathVariable("bookId") Integer bookId){bookService.removeBook(bookId);return "redirect:/index";}}
  
 

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.

 
   
  
   spring01
    
      
   
    index.html
       
   
    index.htm
       
   
    index.jsp
       
   
    default.html
       
   
    default.htm
       
   
    default.jsp
     
      
  
   
    spring
   
   
    org.springframework.web.servlet.DispatcherServlet
   
   
    1
   
  
  
   
    spring
   
   
    /
   
  
 

Now create jdbc.propertiesFile 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.
jdbc.driverClassName=com.mysql.jdbc.Driverjdbc.dialect=org.hibernate.dialect.MySQLDialectjdbc.databaseurl=jdbc:mysql://localhost:3306/testjdbc.username=rootjdbc.password=123456

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

     
 
  
   
  
 

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.

 
 
  
  
  
   
    
     
      
       
      
     
    
    
     
      
     
    
    
     
      
       
        
         
          resources/hibernate.cfg.xml
         
        
        
         
          org.hibernate.cfg.AnnotationConfiguration
         
        
        
         
          
           ${jdbc.dialect}
          
          
           true
          
         
        
       
      
      
       
        
       
      
     
    
   
  
 

View creation

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.

book.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%><%@taglib uri="http://www.springframework.org/tags" prefix="spring"%><%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%><%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<Script type = "text/javascript"> function deleteBook (bookId) {if (confirm ('Do you want to delete this Book? ') {Var url = 'delete/' + bookId; window. location. href = url ;}</script> Book Store-SpringMVC-Hibernate CRUD Application

To add a New Book please click "title =" Add a New Book "/>

List of Books in Library
Book Name Author Name Price Quantity Action
$ {Book. bookName} $ {Book. author} $ {Book. price} $ {Book. quantity} "Title =" Delete Book "/>" title = "Edit Book"/>






Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.