CRUD OPERATIONS USING SPRING MVC AND HIBERNATE
Lets Start with What is CRUD? CRUD stands for
C- Create R-RetrieveU-Update D-Delete
Manipulating Data in Database i.e. Inserting , Updating , Deleting and Retriving data is known as CRUD operation. In Short, we are going to perform DML operations on database through our Spring MVC Web Application.
Here we are going to use H2 database for persisting data, Eclipse Maven Quickstart Project for Backend. Eclipse Maven Web-App for FrontEnd.
What is Hibernate? Well in short, it is an ORM tool, i.e. Object Relational mapping tool to Map your class objects to Table row.
Lets Start to Build our Project..... 😃
First Lets Create a Table Product in our H2 database.
1. Open H2 Console (Desktop app).
2. Connect using Right Credentials you have set. In my case Username is 'sa' and password is blank.
3.Write below Query to create table Product
Create Table Product
(
product_id int primary Key,
product_name varchar2(25),
qty double,
price double,
description varchar2(100)
);
4. Run the Query. Your Product Table is Ready.
Now Lets Start With BackEnd Project. Here we will create models and use DAO pattern to access data from Database.
1. Create a maven quickstart project with appropriate artifact-id and group-id.
2. Change JRE, Compiler to jdk 1.8
2. Create a package in src/main/java folder , here i am creating package with name
com.education.model.
3. create a POJO class which represents Product table Entity. as shown below.
package com.education.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import org.springframework.stereotype.Component;
@Component
@Entity
@Table
public class Product {
@Id
int product_id;
@Column
String product_name;
@Column
double qty;
@Column
double price;
@Column
String description;
public int getProduct_id() {
return product_id;
}
public void setProduct_id(int product_id) {
this.product_id = product_id;
}
public String getProduct_name() {
return product_name;
}
public void setProduct_name(String product_name) {
this.product_name = product_name;
}
public double getQty() {
return qty;
}
public void setQty(double qty) {
this.qty = qty;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
@Component: The @Component
annotation marks a java class as a bean so the component-scanning mechanism of spring can pick it up and pull it into the application context for dependency Injection.
@Entity: Specifies that the class is an entity. This annotation is applied to the entity class
@Table: Specifies the primary table for the annotated entity. If no name is provided it will map with same name table as entity class name.
@Column: Specifies the Columns of table for the annotated table. If no name is provided it will map with same name columns as class attributes name.
@Id: Specifies unique Identifier for records . Generally its a primary key of table.
@Component
annotation marks a java class as a bean so the component-scanning mechanism of spring can pick it up and pull it into the application context for dependency Injection.
4. For above annotations you need to add following dependencies in pm.xml file
5. Now Create another package for Data Access Object(DAO Pattern). here i am creating com.education.dao package.
6. Create an Interface having manupulation abstract method as shown below.
package com.education.dao;
import java.util.List;
import com.education.model.Product;
public interface ProductDAO {
public List < Product > getAllProduct();
public boolean save(Product p);
public boolean deleteById(int id);
public boolean update(Product p);
public Product getById(int id);
}
7. Create an Implementation of above interface as shown below:
package com.education.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 org.springframework.transaction.annotation.Transactional;
import com.education.model.Product;
@Repository("productDAO")
@Transactional
public class ProductDAOImpl implements ProductDAO {
@Autowired
SessionFactory sessionFactory;
@Override
public List < Product > getAllProduct() {
Session session = sessionFactory.openSession();
Query query = session.createQuery("from Product"); // HQL is used here
// not SQL
List < Product > productlist = query.list();
session.close();
return productlist;
}
@Override
public boolean save(Product p) {
try {
Session session = sessionFactory.openSession();
session.save(p);
session.flush();
session.close();
} catch (Exception e) {
return false;
}
return true;
}
@Override
public boolean deleteById(int id) {
try {
Session session = sessionFactory.openSession();
Product p = (Product) session.get(Product.class, id);
if (p == null)
return false;
session.delete(p);
session.flush();
session.close();
} catch (Exception e) {
return false;
}
return true;
}
@Override
public boolean update(Product p) {
try {
Session session = sessionFactory.openSession();
session.update(p);
session.flush();
session.close();
} catch (Exception e) {
return false;
}
return true;
}
@Override
public Product getById(int id) {
Session session = sessionFactory.openSession();
Product p = (Product) session.get(Product.class, id);
session.close();
return p;
}
}
@Repository: @Repository
annotation is a specialization of the @Component
annotation with similar use and functionality.
In addition to importing the DAOs into the DI container, it
also makes the unchecked exceptions (thrown from DAO methods) eligible for
translation into
Spring DataAccessException
@Autowired: We can use Spring @Autowired annotation for spring bean autowiring. @Autowired annotation can be applied on variables and methods for autowiring byType. We can also use @Autowired annotation on constructor for constructor based spring autowiring.
@Transactional: It is used to specify that the methods will run in an transaction which will follow ACID property of Data Management. The value attribute of the @Transactional annotation is not mandatory. If not mentionned Spring will look by default for any bean declared in the context with the name “transactionManager” (defaultConvention).
8. Create a new package com.education.config and create a class for configuring database of your choice . you can do it using xml file in web-app but here i have used annotation based configuration
package com.education.config;
import java.util.Properties;
import org.apache.commons.dbcp2.BasicDataSource;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.orm.hibernate4.LocalSessionFactoryBuilder;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@Configuration
@ComponentScan("com.education")
@EnableTransactionManagement
public class AnnotationConfig {
@Autowired
@Bean(name = "dataSource")
public DataSource getDataSource() {
BasicDataSource dataSource = new BasicDataSource();
// DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("org.h2.Driver");
dataSource.setUrl("jdbc:h2:~/test");
dataSource.setUsername("sa"); // Schema name
dataSource.setPassword("");
return dataSource;
}
private Properties getHibernateProperties() {
Properties p = new Properties();
p.put("hibernate.dialect", "org.hibernate.dialect.H2Dialect");
p.put("hibernate.show_sql", "true");
p.put("hibernate.hbm2ddl.auto", "update");
return p;
}
@Autowired
@Bean(name = "sessionFactory")
public SessionFactory getSessionFactory(DataSource dataSource) {
LocalSessionFactoryBuilder sessionBuilder = new LocalSessionFactoryBuilder(dataSource);
sessionBuilder.addProperties(getHibernateProperties());
sessionBuilder.scanPackages("com.education");
return sessionBuilder.buildSessionFactory();
}
@Autowired
@Bean(name = "transactionManager")
public HibernateTransactionManager getTransactionManager(SessionFactory sessionFactory) {
HibernateTransactionManager transactionManager = new HibernateTransactionManager(sessionFactory);
return transactionManager;
}
}
Here you are Done with your Backend Project.. You can use Junit Testing to test all dao methods. But here we are limiting ourselves to crud operation only. We may cover Junit in later post.
Lets Start With our Front End Project ..... 😄
1. Create another project with Maven Web-App Artifact. I am using artifact as com.education and group id as FrontEnd.
2. We will do all Crud Operation on one Single jsp Page consider it as home.jsp.
3.Before we start dont forget to add dependency of backend project to frontend project and also few dependency required for jsp and spring mvc to work as shown below.
4. create a folder pages in WEB-INF folder and create a jsp page home.jsp as shown below.
5. Create a Controller class in src/main/java in package com.education.controllers as shown below.
package com.education.controllers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
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.education.dao.ProductDAO;
import com.education.model.Product;
@Controller
public class ProductController {
@Autowired
ProductDAO productDAO;
// Landing Page--product is added in Model for Spring Form---List is added
// to retrive all data
@RequestMapping("/")
public String home(Model m) {
m.addAttribute("isEditing", false);
m.addAttribute("product", new Product());
m.addAttribute("productList", productDAO.getAllProduct());
m.addAttribute("msg", "");
return "home";
}
// Saving Product
@RequestMapping(value = "/save", method = RequestMethod.POST)
public String save(@ModelAttribute("product") Product p, Model m) {
productDAO.save(p);
m.addAttribute("product", new Product());
m.addAttribute("productList", productDAO.getAllProduct());
m.addAttribute("msg", "product added successfully");
return "home";
}
// Displaying Update Form
@RequestMapping(value = "/update/{pid}", method = RequestMethod.GET)
public String update(@PathVariable("pid") int pid, Model m) {
Product p = productDAO.getById(pid);
m.addAttribute("isEditing", true);
m.addAttribute("product", p);
m.addAttribute("productList", productDAO.getAllProduct());
m.addAttribute("msg", "");
return "home";
}
// Updating Product
@RequestMapping(value = "/update", method = RequestMethod.POST)
public String update(@ModelAttribute("product") Product p, Model m) {
productDAO.update(p);
m.addAttribute("product", new Product());
m.addAttribute("productList", productDAO.getAllProduct());
m.addAttribute("msg", "product updated successfully");
return "home";
}
// Deleting Product
@RequestMapping(value = "/delete/{pid}", method = RequestMethod.GET)
public String delete(@PathVariable("pid") int pid, Model m) {
productDAO.deleteById(pid);
m.addAttribute("product", new Product());
m.addAttribute("productList", productDAO.getAllProduct());
m.addAttribute("msg", "product deleted successfully");
return "home";
}
}
6. Configure Dispatcher Servlet in web.xml as shown below.
7. Configure dispatcher-servlet.xml file as shown below.
8.Run your app... your Crud Project is Ready....😁
9. For Any Errors or Clarification please feel free to Comment.
(adsbygoogle = window.adsbygoogle || []).push({
google_ad_client: "ca-pub-7220567598236421",
enable_page_level_ads: true
});
package com.education.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 org.springframework.transaction.annotation.Transactional;
import com.education.model.Product;
@Repository("productDAO")
@Transactional
public class ProductDAOImpl implements ProductDAO {
@Autowired
SessionFactory sessionFactory;
@Override
public List < Product > getAllProduct() {
Session session = sessionFactory.openSession();
Query query = session.createQuery("from Product"); // HQL is used here
// not SQL
List < Product > productlist = query.list();
session.close();
return productlist;
}
@Override
public boolean save(Product p) {
try {
Session session = sessionFactory.openSession();
session.save(p);
session.flush();
session.close();
} catch (Exception e) {
return false;
}
return true;
}
@Override
public boolean deleteById(int id) {
try {
Session session = sessionFactory.openSession();
Product p = (Product) session.get(Product.class, id);
if (p == null)
return false;
session.delete(p);
session.flush();
session.close();
} catch (Exception e) {
return false;
}
return true;
}
@Override
public boolean update(Product p) {
try {
Session session = sessionFactory.openSession();
session.update(p);
session.flush();
session.close();
} catch (Exception e) {
return false;
}
return true;
}
@Override
public Product getById(int id) {
Session session = sessionFactory.openSession();
Product p = (Product) session.get(Product.class, id);
session.close();
return p;
}
}
@Repository
annotation is a specialization of the @Component
annotation with similar use and functionality.
In addition to importing the DAOs into the DI container, it
also makes the unchecked exceptions (thrown from DAO methods) eligible for
translation into
Spring DataAccessException
package com.education.controllers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
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.education.dao.ProductDAO;
import com.education.model.Product;
@Controller
public class ProductController {
@Autowired
ProductDAO productDAO;
// Landing Page--product is added in Model for Spring Form---List is added
// to retrive all data
@RequestMapping("/")
public String home(Model m) {
m.addAttribute("isEditing", false);
m.addAttribute("product", new Product());
m.addAttribute("productList", productDAO.getAllProduct());
m.addAttribute("msg", "");
return "home";
}
// Saving Product
@RequestMapping(value = "/save", method = RequestMethod.POST)
public String save(@ModelAttribute("product") Product p, Model m) {
productDAO.save(p);
m.addAttribute("product", new Product());
m.addAttribute("productList", productDAO.getAllProduct());
m.addAttribute("msg", "product added successfully");
return "home";
}
// Displaying Update Form
@RequestMapping(value = "/update/{pid}", method = RequestMethod.GET)
public String update(@PathVariable("pid") int pid, Model m) {
Product p = productDAO.getById(pid);
m.addAttribute("isEditing", true);
m.addAttribute("product", p);
m.addAttribute("productList", productDAO.getAllProduct());
m.addAttribute("msg", "");
return "home";
}
// Updating Product
@RequestMapping(value = "/update", method = RequestMethod.POST)
public String update(@ModelAttribute("product") Product p, Model m) {
productDAO.update(p);
m.addAttribute("product", new Product());
m.addAttribute("productList", productDAO.getAllProduct());
m.addAttribute("msg", "product updated successfully");
return "home";
}
// Deleting Product
@RequestMapping(value = "/delete/{pid}", method = RequestMethod.GET)
public String delete(@PathVariable("pid") int pid, Model m) {
productDAO.deleteById(pid);
m.addAttribute("product", new Product());
m.addAttribute("productList", productDAO.getAllProduct());
m.addAttribute("msg", "product deleted successfully");
return "home";
}
}
9. For Any Errors or Clarification please feel free to Comment.
(adsbygoogle = window.adsbygoogle || []).push({
google_ad_client: "ca-pub-7220567598236421",
enable_page_level_ads: true
});
No comments:
Post a Comment