Spring & Hibernate CRUD with SQL

Spring And Hibernate CRUD Application with SQL


This is just an example to illustrate the integration of Spring & Hibernate with MySQL database. There is all the required APIs are give by the pom.xml (all dependencies are given here). All the packages having its own meaning like controller, doa, service etc.
Pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>Demo</groupId>
  <artifactId>Demo</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  <build>
    <sourceDirectory>src</sourceDirectory>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.7.0</version>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>
      <plugin>
        <artifactId>maven-war-plugin</artifactId>
        <version>3.2.1</version>
        <configuration>
          <warSourceDirectory>WebContent</warSourceDirectory>
        </configuration>
      </plugin>
    </plugins>
  </build>
<properties>
<java-version>1.8</java-version>
<org.springframework-version>4.3.18.RELEASE</org.springframework-version>
<org.aspectj-version>1.6.10</org.aspectj-version>
<org.slf4j-version>1.6.6</org.slf4j-version>
<hibernate.version>4.3.5.Final</hibernate.version>
<hibernate.validator.version>5.1.2.Final</hibernate.validator.version>
<c3p0>0.9.5.2</c3p0>
<tiles_core>3.0.3</tiles_core>
<javax.validation.version>1.1.0.Final</javax.validation.version>
</properties>
<dependencies>

<!-- https://mvnrepository.com/artifact/com.fasterxml/classmate --> <dependency>     <groupId>com.fasterxml</groupId>     <artifactId>classmate</artifactId>     <version>0.8.0</version> </dependency>


<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${org.springframework-version}</version>
<exclusions>
<!-- Exclude Commons Logging in favor of SLF4j -->
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${org.springframework-version}</version>
</dependency>
    <!-- https://mvnrepository.com/artifact/org.springframework/spring-web -->        <dependency>           <groupId>org.springframework</groupId>           <artifactId>spring-web</artifactId>           <version>${org.springframework-version}</version>        </dependency>
    <!-- https://mvnrepository.com/artifact/org.springframework/spring-orm -->         <dependency>             <groupId>org.springframework</groupId>             <artifactId>spring-orm</artifactId>             <version>${org.springframework-version}</version>         </dependency>
    <!-- https://mvnrepository.com/artifact/org.springframework/spring-context-support -->         <dependency>            <groupId>org.springframework</groupId>            <artifactId>spring-context-support</artifactId>            <version>${org.springframework-version}</version>         </dependency>
    <!-- https://mvnrepository.com/artifact/org.springframework/spring-beans -->        <dependency>           <groupId>org.springframework</groupId>           <artifactId>spring-beans</artifactId>           <version>${org.springframework-version}</version>        </dependency>
    <!-- https://mvnrepository.com/artifact/org.springframework/spring-tx -->       <dependency>            <groupId>org.springframework</groupId>            <artifactId>spring-tx</artifactId>            <version>${org.springframework-version}</version>       </dependency>       <!-- https://mvnrepository.com/artifact/org.springframework.security/spring-security-crypto -->      <dependency>         <groupId>org.springframework.security</groupId>         <artifactId>spring-security-crypto</artifactId>         <version>4.2.7.RELEASE</version>      </dependency>
       
  <!-- Spring End -->   

<!-- Spring AOP + AspectJ -->

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${org.springframework-version}</version>
</dependency>
    <dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>${org.aspectj-version}</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>${org.aspectj-version}</version>
</dependency>


<!-- Logging -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${org.slf4j-version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>${org.slf4j-version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${org.slf4j-version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.15</version>
<exclusions>
<exclusion>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
</exclusion>
<exclusion>
<groupId>javax.jms</groupId>
<artifactId>jms</artifactId>
</exclusion>
<exclusion>
<groupId>com.sun.jdmk</groupId>
<artifactId>jmxtools</artifactId>
</exclusion>
<exclusion>
<groupId>com.sun.jmx</groupId>
<artifactId>jmxri</artifactId>
</exclusion>
</exclusions>
<scope>runtime</scope>
</dependency>
<!-- @Inject -->
<dependency>
<groupId>javax.inject</groupId>
<artifactId>javax.inject</artifactId>
<version>1</version>
</dependency>

<!-- Servlet -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>

    <!-- Hibernate -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>             <groupId>org.hibernate</groupId>             <artifactId>hibernate-c3p0</artifactId>             <version>${hibernate.version}</version>         </dependency>
        <!-- jsr303 validation dependencies-->         <dependency>             <groupId>javax.validation</groupId>             <artifactId>validation-api</artifactId>             <version>${javax.validation.version}</version>         </dependency>
         <dependency>             <groupId>org.hibernate</groupId>             <artifactId>hibernate-validator</artifactId>             <version>${hibernate.validator.version}</version>         </dependency>
<!--  Hibernate End -->
      <!-- Tiles -->
<dependency>
<groupId>org.apache.tiles</groupId>
<artifactId>tiles-jsp</artifactId>
<version>${tiles_core}</version>
</dependency>
<dependency>
<groupId>org.apache.tiles</groupId>
<artifactId>tiles-core</artifactId>
<version>${tiles_core}</version>
</dependency>
     <!--  Tiles End-->
<!-- Other -->
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20180130</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.3.4</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>${c3p0}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.6</version>
</dependency>
            <!-- Other End -->
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->        <dependency>          <groupId>mysql</groupId>          <artifactId>mysql-connector-java</artifactId>          <version>8.0.11</version>        </dependency>

<!-- Test -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.7</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>


Constants.java

package com.demo.constants;
public class Constants {
    public static final String PATH_HOME_PAGE = "/home";     public static final String REGISTER_EMPLOYEE = "/register";     public static final String GOTO_EMPLOYEE_LIST = "/goto";     public static final String DELETE_EMPLOYEE = "/deleteEmployee";///{id}     public static final String UPDATE_EMPLOYEE = "/updateProcess";     public static final String UPDATE_BUTTON = "/update";     public static final String Employee_LIST="employeeList";     public static final String SEARCH_EMPLOYEE="/search";
}



EmployeeController.java

 package com.demo.controller;
import java.util.ArrayList; import java.util.List; import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import com.demo.service.EmployeeService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.ui.ModelMap; 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.springframework.web.bind.annotation.RequestParam;
import com.demo.model.Employee;
import com.demo.constants.Constants;
/**  * @author: Suraj Pratap Singh  * @Info: EmployeeController  */ @Controller @RequestMapping("/") public class EmployeeController {     private static final Logger LOGGER = Logger.getLogger ( EmployeeController.class.getName () );
    public static int updateId;     @Autowired     private EmployeeService employeeService;
    /**      * @param model :      * @return home JSP      * @implNote :      */     @RequestMapping(value = Constants.PATH_HOME_PAGE)     public String homePage(ModelMap model) {         return "home";     }
    /**      * @return employeeList JSP page      */     @RequestMapping(value = Constants.REGISTER_EMPLOYEE)     public String registerData(@ModelAttribute("employee") Employee employee, HttpServletRequest request, Model model) {         employeeService.save ( employee );         String msg = "Employee Registered Successfully....";         LOGGER.info ( msg );         model.addAttribute ( "msg", msg );         return Constants.PATH_HOME_PAGE;
    }
    /**      * @param model      * @return employeeList JSP page      * Purpose: It will redirect to Employee List      */     @RequestMapping(value = Constants.GOTO_EMPLOYEE_LIST)     public String gotoEmployeeList(Model model) {
        List <Employee> employeeData = employeeService.getAllEmployeeData ();         if (employeeData != null) {             model.addAttribute ( "employeeList", employeeData );         }         return "employeeList";     }
    /**      * @param id      * @return redirect:/goto      * Purpose: It will delete employee then redirect to employeeList      */     @RequestMapping(value = Constants.DELETE_EMPLOYEE)     public String deleteEmployee(@RequestParam("id") int id, Model model) {         String msg = "Successfully deleted...";         try {             employeeService.delete ( id );             model.addAttribute ( "msg", msg );
        } catch (Exception ex) {             LOGGER.warning ( ex.getMessage () );         }         LOGGER.info ( "Employee Deleted Successfully..." );         return "update";     }
    /**      * @param employee      * @return redirect:/goto      * Purpose: Update employee details then redirect to employeeList      */     @RequestMapping(value = Constants.UPDATE_EMPLOYEE)     public String updateRecord(@ModelAttribute("employee") Employee employee, Model model) {         try {             employeeService.update ( employee );         } catch (Exception e) {             LOGGER.warning ( e.getMessage () );         }         String msg = "Employee record updated Successfully...";         model.addAttribute ( "msg", msg );
        return "update";     }
    /**      * @return update      * Purpose: It will get employee data and redirect to update form      */     @RequestMapping(value = Constants.UPDATE_BUTTON)     public String employeeList1(/*@RequestParam("id") int id, Model model*/) {         /*Employee employee = employeeService.getEmployee ( id );         model.addAttribute ( "employee", employee );*/         return "update";     }
    /**      * @param id      * @param model      * @return employeeList JSP      * Purpose: This method is used to search by Id      */     @RequestMapping(value = "/searchById")     public String searchById(@RequestParam("id") int id, Model model) {         Employee emp1 = null;         emp1 = employeeService.getEmployee ( id );
        String msg = "Search by id \"Employee Not Found\"";         if (emp1 != null) {             model.addAttribute ( "employee", emp1 );         } else {             model.addAttribute ( "msg", msg );             return "search";         }
        return "update";     }
    /**      * Purpose: It will redirect to search page      *      * @return search JSP      */     @RequestMapping(value = "/search")     public String searchPage() {         return "search";     }
    /**      * @param mobileNumber      * @param model      * @return employeeList JSP      * Purpose: Search employee by contact      */     @RequestMapping(value = "/searchByContact")     public String searchByContact(@RequestParam("mobileNumber") String mobileNumber, Model model) {         String msg = "Search by contact \"No record found!\" ";         List <Employee> list = employeeService.getByContact ( mobileNumber );         if (list.isEmpty ()) {             model.addAttribute ( "msg", msg );             return "search";         } else {             model.addAttribute ( "employeeList", list );         }         return "employeeList";     } }


IEmployeeDao.java

 package com.demo.dao;
import java.util.List;
import com.demo.model.Employee;
/**  * @Author: Suraj Pratap Singh  * {@link com.demo.dao.impl.EmployeeDaoImpl}  */ public interface IEmployeeDao {
    void save(Employee employee);
    void update(Employee employee);
    void delete(int id);
    Employee getEmployee(int id);
    List <Employee> getAllEmployeeData();     List<Employee> getByContact(String mobileNumber); }

EmployeeDaoImpl.java

package com.demo.dao.impl;
import java.util.List;
import javax.transaction.Transactional;
import com.demo.dao.IEmployeeDao; 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.demo.model.Employee;
/**  * @Author: Suraj pratap singh  * @Purpose: Implementation of IEmployeeDao Interface  */ @Transactional @Repository("IEmployeeDao") public class EmployeeDaoImpl implements IEmployeeDao {

    @Autowired     private SessionFactory sessionFactory;
    /**      * @param employee      * @Info: To save employee object      */     @Override     public void save(Employee employee) {         Session session = sessionFactory.getCurrentSession ();         session.save ( employee );     }
    /**      * @param employee      * @Info: Update Employee Details      */     @Override     public void update(Employee employee) {         Session session = this.sessionFactory.getCurrentSession ();
        session.update ( employee );     }
    /**      * @param employeeId      * @Info: Delete Employee Record      */     @Override     public void delete(int employeeId) {         Employee employee = (Employee) sessionFactory.getCurrentSession ().load (                 Employee.class, employeeId );         if (employee != null) {             this.sessionFactory.getCurrentSession ().delete ( employee );         }     }
    /**      * @return: List<Employee>      */     @Override     public List <Employee> getAllEmployeeData() {         try {
            Session session = sessionFactory.getCurrentSession ();             Query query = session.createQuery ( "from Employee where status='active'" );             List <Employee> list = query.list ();
            return list;
        } catch (Exception exp) {             exp.printStackTrace ();             return null;         }     }
    /**      * @param id      * @return Employee Object      */     @Override     public Employee getEmployee(int id) {         return (Employee) this.sessionFactory.getCurrentSession ().get ( Employee.class, id );     }
    @Override     public List<Employee> getByContact(String mobileNumber)     {
        String query="from Employee where mobileNumber=:mn";         Session session=this.sessionFactory.getCurrentSession ();         Query query1=session.createQuery(query);         query1.setString ( "mn",mobileNumber );         List<Employee> list=query1.list ();         return list;     } }



Employee.java

 package com.demo.model;
import java.io.Serializable; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table;
/**  * @Author: Suraj Pratap Singh  * @Purpose: Employee Entity (Table)  */ @Entity @Table(name = "employee") public class Employee implements Serializable {     private static final long serialVersionUID = 7648340269375550863L;
    @Id     @GeneratedValue(strategy = GenerationType.AUTO)     private int id;     private String firstName;     private String lastName;     private String address;     private long mobileNumber;     private String designation;     private int salary;     private String status;
    public static long getSerialVersionUID() {         return serialVersionUID;     }
    public int getId() {         return id;     }
    public void setId(int id) {         this.id = id;     }
    public String getFirstName() {         return firstName;     }
    public void setFirstName(String firstName) {         this.firstName = firstName;     }
    public String getLastName() {         return lastName;     }
    public void setLastName(String lastName) {         this.lastName = lastName;     }
    public String getAddress() {         return address;     }
    public void setAddress(String address) {         this.address = address;     }
    public long getMobileNumber() {         return mobileNumber;     }
    public void setMobileNumber(long mobileNumber) {         this.mobileNumber = mobileNumber;     }
    public String getDesignation() {         return designation;     }
    public void setDesignation(String designation) {         this.designation = designation;     }
    public int getSalary() {         return salary;     }
    public void setSalary(int salary) {         this.salary = salary;     }
    public String getStatus() {         return status;     }
    public void setStatus(String status) {         this.status = status;     } }

EmployeeService.java

package com.demo.service;
import com.demo.model.Employee;
import java.util.List;
/**  * @Author: Suraj Pratap Singh  * @Purpose: interface EmployeeService  */ public interface EmployeeService {     void save(Employee employee);
    void update(Employee employee);
    void delete(int id);
    Employee getEmployee(int id);
    List <Employee> getAllEmployeeData();
    List<Employee> getByContact(String mobileNumber); }

EmployeeServiceImpl.java

package com.demo.service.serviceImpl;
import com.demo.dao.IEmployeeDao; import com.demo.model.Employee; import com.demo.service.EmployeeService; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service;
import java.util.ArrayList; import java.util.List;
/**  * Purpose: To perform CRUD operations of Employees in database  * like Add, Delete , Update , Read Employee information.  *  * @author: Suraj Pratap Singh  */
@Service public class EmployeeServiceImpl implements EmployeeService {     @Autowired     private IEmployeeDao employeeDao;
    @Override     public void save(Employee employee) {         employee.setStatus ( "active" );         employeeDao.save ( employee );     }
    @Override     public void update(Employee employee) {         employeeDao.update ( employee );     }
    @Override     public void delete(int id) {         Employee employee=employeeDao.getEmployee ( id );         employee.setStatus ( "inactive" );         employeeDao.update ( employee );     }
    @Override     public Employee getEmployee(int id) {         Employee emp=employeeDao.getEmployee ( id );
        if(emp!=null) {             if (emp.getStatus ().equals ( "inactive" )) {                 emp = null;             }         }         return emp;     }
    @Override     public List <Employee> getAllEmployeeData() {
        return employeeDao.getAllEmployeeData ();     }
    @Override     public List <Employee> getByContact(String mobileNumber) {         List<Employee> emp=employeeDao.getByContact ( mobileNumber);         List<Employee> emp1=new ArrayList <> (  );         for(Employee employee: emp){             if(employee.getStatus().equals ( "active" )){                 emp1.add ( employee );             }         }         return emp1;     }
}

Comments

Popular Posts