Spring Mvc With Hibernate ,MySQL,Maven Integration CRUD Example

Spring Mvc With Hibernate ,MySQL,Maven Integration CRUD Example

In This Article I would like to explain How To Integrate Spring mvc With Hibernate ,MySQL and Maven and We will See One basic CRUD Operations Example.

The Project Structure



Tools Used In this Article
JavaFrameworksDatabaseSetverTools
Java 1.8Spring 4.3.2
Hibernate 4.3.2
MySQLTomcat 8.0.43Maven 4.0.0
Ecclipse Neon
Add Maven Dependenciespom.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>SpringMvcDemo</groupId>
<artifactId>SpringMvcDemo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.3.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>4.3.2.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.2.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.8</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.3.2.Final</version>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>

</dependencies>
<build>
<sourceDirectory>src</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>2.4</version>
<configuration>
<warSourceDirectory>WebContent</warSourceDirectory>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</build>

</project>
web.xml

<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
;xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0"
>
<display-name>Spring MVC Web Application</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<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>
</web-app>

In web.xml we have declared dispatcher servlet which is known as front controller.

Now create Spring configuration file spring-servlet.xml

spring-servlet.xml

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"
>

<context:component-scan base-package="com.java2study" />
<bean id="dataSource"
class
="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<t;property name="url" value="jdbc:mysql://localhost:3306/bala" />
<property name="username" value="root" />
<property name="password" value="root123" />
</bean>

<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>com.java2study.model.Laptop</value>
<list>
<property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<props>
<property>
</bean>
<bean id="txManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/jsps/</value>
<property>
<property name=class = "jvariable">"suffix">
<value>.jsp<value>
<property>
</bean>
<mvc:annotation-driven />
</beans>

create Model class

Laptop.java

package com.java2study.model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
@Table
@Entity
public class Laptop implements Serializable{
@Id
@GeneratedValue
private int laptopId;
@Column
private String name;
@Column
private double price;
public int getLaptopId() {
return laptopId;
}
public void setLaptopId(int laptopId) {
this.laptopId = laptopId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}


}

Create Dao Classes

LaptopDao.java

package com.java2study.dao;
import java.util.List;
import com.java2study.model.Laptop;
public interface LaptopDao {
public void addLaptop(Laptop laptop);
public List listLaptop();
public Laptop getLaptopById(int laptopId);
public void updateLaptop(Laptop laptop);
public void deletelaptop(int laptopId);
}
LaptopDaoImpl.java

package com.java2study.dao;
import java.io.Serializable;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.java2study.model.Laptop;
@Repository
public class LaptopDaoImpl implements LaptopDao {
@Autowired
private SessionFactorysessionFactory;

@Override
public void addLaptop(Laptop laptop) {

Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
session.save(laptop);
tx.commit();
session.close();

}
@Override
public List listLaptop() {
Session session=sessionFactory.openSession();
Query query=session.createQuery("from Laptop l");
List list=query.list();
session.close();
return list;
}
@Override
public Laptop getLaptopById(int laptopId) {
// TODO Auto-generated method stub
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
Laptop laptop = (Laptop)session.get(Laptop.class, laptopId);
tx.commit();
session.close();
return laptop;
}
@Override
public void updateLaptop(Laptop laptop)
{
Session session=sessionFactory.openSession();
Transaction tx = session.beginTransaction();

session.saveOrUpdate(laptop);
System.out.println("update..................");
tx.commit();
session.close();
}
@Override
public void deletelaptop(int laptopId) {
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
Laptop laptop = (Laptop) session.get(Laptop.class, laptopId);
session.delete(laptop);
tx.commit();
session.close();

}

}

we need to declare the Dao implementation class with @Repository annotation.

Now create Service classes

LaptopService.java

package com.java2study.service;
>import java.util.List;
import com.java2study.model.Laptop;
public interface LaptopService {
public void addLaptop(Laptop laptop);
public List listLaptop();
public Laptop getLaptopById(int laptopId);
public void updateLaptop(Laptop laptop);
public void deletelaptop(int laptopId);

}

package com.java2study.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.java2study.dao.LaptopDao;
import com.java2study.model.Laptop;
@Service
public class LaptopServiceImpl implements LaptopService {
@Autowired
private LaptopDao laptopDao;
@Override
public void addLaptop(Laptop laptop) {
// TODO Auto-generated method stub
laptopDao.addLaptop(laptop);
}

@Override
public List listLaptop() {
return laptopDao.listLaptop();
}

@Override
public Laptop getLaptopById(int laptopId) {
// TODO Auto-generated method stub
return laptopDao.getLaptopById(laptopId);
}

@Override
public void updateLaptop(Laptop laptop) {
// TODO Auto-generated method stub
laptopDao.updateLaptop(laptop);

}

@Override
public void deletelaptop(int laptopId) {
laptopDao.deletelaptop(laptopId);

}

}

We need to declare the Service implementatioin class with @Service annotation.

Now create Controller class and annotate with @Controller

LaptopController.java

package com.java2study.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.java2study.model.Laptop;
import com.java2study.service.LaptopService;
@Controller
public class LaptopController {
@Autowired(required=true)
private LaptopService laptopService;


@RequestMapping("/welcome")
public String welcome(Model model) {
Laptop laptop = new Laptop();
model.addAttribute("laptop", laptop);
return "laptopform";

}
@RequestMapping("addLaptop")
public ModelAndView registerUser(@ModelAttribute("laptop") Laptop laptop,BindingResult result
) {
System.out.println("hello");

laptopService.addLaptop(laptop);
return new ModelAndView("redirect:listlaptop");
}
@RequestMapping("listlaptop")
public ModelAndView getList() {
List laptopList = laptopService.listLaptop();
return new ModelAndView("listlaptop","laptopList",laptopList);
}
@RequestMapping("edit")
public ModelAndView editLaptop(@RequestParam int laptopId,@ModelAttribute Laptop laptop) {
System.out.println("i love you");
Laptop laptopObject = laptopService.getLaptopById(laptopId);
return new ModelAndView("Edit","laptopObject",laptopObject);
}
@RequestMapping("update")
public ModelAndView update(@ModelAttribute Laptop laptop) {

laptopService.updateLaptop(laptop);

return new ModelAndView("redirect:listlaptop");
}
@RequestMapping("delete")
public ModelAndView deleteLaptop(@RequestParam int laptopId) {
laptopService.deletelaptop(laptopId);
return new ModelAndView("redirect:listlaptop");
}
}

Now create View Pages

laptopform.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<style type="text/css">
form {
border: 1px solid #cdcdcd;
width: 32%;
background: lightblue;
border-radius: 4px;
align: center;
margin-left: 310px;
padding-left:100px;
padding-right:100px;
}
.td{
font-size:16px;
}
</style>
</head>
<body>
<form:form modelAttribute="laptop" method="post" action="addLaptop">

<table>
<tr>
<td style = "font-size:20px;">Laptop name:</td>
<td><form:input path="name" /></td>
</tr>
<tr>
<td style = "font-size:20px;">Price:</td>
<td><form:input path="price" /></td>
</tr>
<tr>
<td colspan="3" align="center" ><input style = "border-radius: 6px;text-align: center; width:113px;height:28px;"
type="submit" value="AddLaptop" />
</td>
</tr>
</table>
</form:form>

</body>
</html>
listlaptop.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<style type="text/css">

tr{
background:#fff;
border:1px solid #cdcdcd;
}
.button {
background-color:#0085be ;
border: none;
color: white;
padding: 15px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin: 4px 2px;
cursor: pointer;
}
table tbody tr th{
padding:10px;
}
</style>
</head>
<body>
<h1>List Of Laptop Details:</h1>
<c:if test="${!empty laptopList}">
<table border="1" style = "border-collapse: collapse;">
<tr>

<th>Laptop ID</th>
<th>Laptop Name</th>
<th>Price</th>
<th>Edit</th>
<th>Delete</th>
<th>ADD</th>

</tr>
<c:forEach items="${laptopList}" var="laptop">
<tr>
<td><c:out value="${laptop.laptopId}" />
<td><c:out value="${laptop.name}" />
</td>
<td><c:out value="${laptop.price}" />
</td>
<td><a href="edit?laptopId=${laptop.laptopId}"><input type="button" class="button" value="Edit"></a></td>
<td><a href="delete?laptopId=${laptop.laptopId}"><input type="button" class="button" value="Delete"></a></td>
<td><a href="welcome"><input type="button" class="button" value="Add"></a></td>
</tr>
</c:forEach>
</table>
</c:if>

</body>
</html>
Edit.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
</head>
<body>
<h1>Edit Laptop Details:</h1>
<form:form modelAttribute="laptop" method="post" action="update">
<table>
<tr>
<td>Laptop ID:</td>
<td><form:input path="laptopId" value="${laptopObject.laptopId}" /></td>
</tr>
<tr>
<td><form:label path="name">Laptop Name:</form:label></td>
<td><form:input path="name" value="${laptopObject.name}"/></td>
</tr>
<tr>
<td>Price:</td>
<td><form:input path="price" value="${laptopObject.price}" /></td>
</tr>
<tr>
<td><input type="submit" value="update" />
</td>
</tr>
</table>
</form:form>
</body>
</html>

Now Run This Web application as Run As-->Run on server in Ecclipse

Output

-->