Sponsored Links
Ad by Google
In my previous post, I have posted about Named Query and How to use named query here. After posting dozens of Hibernate Tutorial and Interview Questions on the internet, today I thought now the time has come to integrate two popular framework together. So in this post, I am going to show you a simple CRUD example of Hibernate with Spring 4 MVC integration. For those who are totally new to Spring MVC or want to learn step by step Hello World Tutorial in Spring MVC they can follow my previous spring mvc tutorial with example.
Of course at the end of this article you can download the full crud example using our downloadable link. While implementing this tutorial, If you are encountered with java.lang.ClassNotFoundException: org.springframework.web.servlet.DispatcherServlet, exception than you can follow How to fix java.lang.ClassNotFoundException to fix the issue.
After completion of this tutorial our output will looks like screens.
listProduct.htm
product.htm
Overview of the project in eclipse -
Step 1. Create Database script
Now if you run this project, you will get the product listing page mapped with listProduct request, here is the complete url of the first request page, http://localhost:8080/SpringHibernateIntegration/listProduct.htm
Of course at the end of this article you can download the full crud example using our downloadable link. While implementing this tutorial, If you are encountered with java.lang.ClassNotFoundException: org.springframework.web.servlet.DispatcherServlet, exception than you can follow How to fix java.lang.ClassNotFoundException to fix the issue.
After completion of this tutorial our output will looks like screens.
listProduct.htm
product.htm
Tools and Technologies,I am using here:
- JDK 7
- Hibernate 4.3.7
- Spring 4.2
- MySql 5.1.10
- Eclipse Kepler 4.3
- Maven 3.2
- Tomcat 8
Overview of the project in eclipse -
Step 1. Create Database script
CREATE DATABASE `hibernate_tutorial`; USE `hibernate_tutorial`; /*Table structure for table `product` */ DROP TABLE IF EXISTS `product`; CREATE TABLE `product` ( `product_id` int(11) NOT NULL AUTO_INCREMENT, `manufactured_date` datetime DEFAULT NULL, `price` float DEFAULT NULL, `product_code` varchar(255) DEFAULT NULL, `product_name` varchar(255) DEFAULT NULL, `vat` float DEFAULT NULL, `brand` varchar(255) DEFAULT NULL, `made_in` varchar(255) DEFAULT NULL, PRIMARY KEY (`product_id`) ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;Step 2. Create annotated Product.java- Class to mapped the product table with Product entity.
package com.javamakeuse.poc.entity; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = "product") public class Product { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "product_id") private int productId; @Column(name = "product_name") private String productName; @Column(name = "made_in") private String madeIn; private String brand; private float price; public int getProductId() { return productId; } public void setProductId(int productId) { this.productId = productId; } public String getProductName() { return productName; } public void setProductName(String productName) { this.productName = productName; } public String getBrand() { return brand; } public void setBrand(String brand) { this.brand = brand; } public float getPrice() { return price; } public void setPrice(float price) { this.price = price; } public String getMadeIn() { return madeIn; } public void setMadeIn(String madeIn) { this.madeIn = madeIn; } }Step 3. Create HibernateUtility.java - To build session factory.
package com.javamakeuse.poc.util; import org.hibernate.SessionFactory; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.Configuration; import org.hibernate.service.ServiceRegistry; public class HibernateUtility { private static final SessionFactory sessionFactory = buildSessionFactory(); private static SessionFactory buildSessionFactory() { Configuration configuration = new Configuration(); configuration.configure(); ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder() .applySettings(configuration.getProperties()).build(); SessionFactory sessionFactory = configuration .buildSessionFactory(serviceRegistry); return sessionFactory; } public static SessionFactory getSessionFactory() { return sessionFactory; } }Step 4. Create hibernate.cfg.xml file- To provide the database related properties and mapping resources.
<?xml version='1.0' encoding='utf-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="connection.url">jdbc:mysql://localhost:3306/hibernate_tutorial</property> <property name="connection.username">root</property> <property name="connection.password">root</property> <property name="hibernate.current_session_context_class">org.hibernate.context.internal.ThreadLocalSessionContext</property> <property name="dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property> <!-- Echo all executed SQL to stdout --> <property name="show_sql">true</property> <property name="format_sql">true</property> <property name="hbm2ddl.auto">update</property> <mapping class="com.javamakeuse.poc.entity.Product" /> </session-factory> </hibernate-configuration>Step 5. Create ProductDAO interface- To defines the database related method like save,update,delete etc.
package com.javamakeuse.poc.dao; import java.util.List; import com.javamakeuse.poc.entity.Product; public interface ProductDAO { public int save(Product product); public void update(Product product); public Product findById(int id); public List<Product> findAll(); public void deleteById(int id); }Step 6. Create ProductDAOImpl class- To implement the ProductDAO interface and provides the implementation of the methods.
package com.javamakeuse.poc.dao; import java.util.List; import org.hibernate.Query; import org.hibernate.Session; import org.springframework.stereotype.Repository; import com.javamakeuse.poc.entity.Product; import com.javamakeuse.poc.util.HibernateUtility; @Repository public class ProductDAOImpl implements ProductDAO { public int save(Product product) { Session session = HibernateUtility.getSessionFactory().openSession(); session.beginTransaction(); int saved = (Integer) session.save(product); session.getTransaction().commit(); return saved; } public void update(Product product) { Session session = HibernateUtility.getSessionFactory().openSession(); session.beginTransaction(); session.update(product); session.getTransaction().commit(); } public Product findById(int id) { Session session = HibernateUtility.getSessionFactory().openSession(); return (Product) session.get(Product.class, id); } public List<Product> findAll() { Session session = HibernateUtility.getSessionFactory().openSession(); Query query = session.createQuery("from Product p"); return query.list(); } public void deleteById(int id) { Session session = HibernateUtility.getSessionFactory() .getCurrentSession(); session.beginTransaction(); session.delete(findById(id)); session.getTransaction().commit(); } }Step 7. Create ProductService interface- And define the methods need to perform CRUD operations on Product entity.
package com.javamakeuse.poc.service; import java.util.List; import com.javamakeuse.poc.dto.ProductDTO; public interface ProductService { public void saveProduct(ProductDTO productDTO); public void update(ProductDTO productDTO); public ProductDTO getProduct(int id); public void deleteProduct(int id); public List<ProductDTO> getAllProducts(); }Step 8. Create ProductServiceImpl class- To implement the methods defined in the ProductService interface.
package com.javamakeuse.poc.service; import java.util.ArrayList; import java.util.List; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.javamakeuse.poc.dao.ProductDAOImpl; import com.javamakeuse.poc.dto.ProductDTO; import com.javamakeuse.poc.entity.Product; @Service public class ProductServiceImpl implements ProductService { @Autowired private ProductDAOImpl productDAO; @Override public void saveProduct(ProductDTO productDTO) { Product product = new Product(); BeanUtils.copyProperties(productDTO, product); productDAO.save(product); } @Override public void update(ProductDTO productDTO) { Product product = new Product(); BeanUtils.copyProperties(productDTO, product); productDAO.update(product); } @Override public ProductDTO getProduct(int id) { Product product = productDAO.findById(id); ProductDTO productDTO = new ProductDTO(); BeanUtils.copyProperties(product, productDTO); return productDTO; } @Override public void deleteProduct(int id) { productDAO.deleteById(id); } @Override public List<ProductDTO> getAllProducts() { List<ProductDTO> productDtos = new ArrayList<ProductDTO>(); List<Product> products = productDAO.findAll(); if (products != null && !products.isEmpty()) { for (Product product : products) { ProductDTO productDTO = new ProductDTO(); BeanUtils.copyProperties(product, productDTO); productDtos.add(productDTO); } } return productDtos; } }Step 9. Create ProductDTO class- This class will help us to get the data from the form and mapped with Product entity.
package com.javamakeuse.poc.dto; public class ProductDTO { private int productId; private String productName; private String brand; private String madeIn; private float price; public int getProductId() { return productId; } public void setProductId(int productId) { this.productId = productId; } public String getProductName() { return productName; } public void setProductName(String productName) { this.productName = productName; } public String getBrand() { return brand; } public void setBrand(String brand) { this.brand = brand; } public String getMadeIn() { return madeIn; } public void setMadeIn(String madeIn) { this.madeIn = madeIn; } public float getPrice() { return price; } public void setPrice(float price) { this.price = price; } }Step 10. Create ProductController class This is the main controller class, which will treated as controller class and it has all the mappings of the request.
package com.javamakeuse.poc.controller; import java.util.ArrayList; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import com.javamakeuse.poc.dto.ProductDTO; import com.javamakeuse.poc.service.ProductService; @Controller @RequestMapping("/") public class ProductController { @Autowired private ProductService productService; @RequestMapping(value = "/listProduct", method = RequestMethod.GET) public ModelAndView listProduct() { return new ModelAndView("list-product", "products", productService.getAllProducts()); } @RequestMapping(value = "/product", method = RequestMethod.GET) public String addProduct(ModelMap modelMap) { modelMap.addAttribute("product", new ProductDTO()); modelMap.addAttribute("update", false); return "create-product"; } @RequestMapping(value = "/editProduct", method = RequestMethod.GET) public String editPage(ModelMap modelMap, HttpServletRequest request) { int productId = Integer.parseInt(request.getParameter("id")); modelMap.addAttribute("product", productService.getProduct(productId)); modelMap.addAttribute("update", true); return "create-product"; } @RequestMapping(value = "/deleteProduct", method = RequestMethod.GET) public ModelAndView deleteProduct(HttpServletRequest request) { int productId = Integer.parseInt(request.getParameter("id")); productService.deleteProduct(productId); return new ModelAndView("list-product", "products", productService.getAllProducts()); } @RequestMapping(value = "/addProduct") public ModelAndView addProduct(ProductDTO productDTO, BindingResult result) { ModelAndView modelAndView = new ModelAndView("list-product"); if (productDTO.getProductId() > 0) { // update productService.update(productDTO); } else { // add product productService.saveProduct(productDTO); } modelAndView.addObject("products", productService.getAllProducts()); return modelAndView; } }
Now if you run this project, you will get the product listing page mapped with listProduct request, here is the complete url of the first request page, http://localhost:8080/SpringHibernateIntegration/listProduct.htm
Download the complete example from here
Sponsored Links
0 comments:
Post a Comment