Spring MVC Example With Hibernate Integration
Hello Readers, in this tutorial we are going to see how to create a spring MVC web application with Hibernate integration, so this is an example of spring and hibernate integration as well.
In this example you may also learn how to map named
queries from separate xml files.
in the previous tutorial we have seen almost
same example but in that tutorial we have not used any database, so this is the
continuous of that tutorial with MySql database using Hibernate.
Table Of
Content :
-Add the dependencies in pom.xml(1)
-Alien.java(2)
-Alien.java(2)
-AlienDao.java(interface)(3)
-AlienDaoImpl.java(4)
-AlienDaoImpl.java(4)
-Named-queries.hbm.xml(5)
-DaoManager.java(6)
-AlienManager.java(7)
-DaoManager.java(6)
-AlienManager.java(7)
-AlienService.java(8)
-home.jsp(9)
-home.jsp(9)
-views folder inside WEB-INF(10)
(10.1 –addAlien.jsp,
10.2displayAlien.jsp,
10.3displayAllAliens.jp,
10.4-editAlienById.jsp)
-spring-mvc-servlet.xml(11)
(10.1 –addAlien.jsp,
10.2displayAlien.jsp,
10.3displayAllAliens.jp,
10.4-editAlienById.jsp)
-spring-mvc-servlet.xml(11)
-configure
web.xml(12)
-AlienController.java(13)
-Test
the application.
1.Add the
following dependencies in the pom.xml, there are some dependency which are not
required for this project so you may exclude them ex. Spring-jdbc.
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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>SpringPractice</groupId>
<artifactId>SpringPractice</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>SpringPractice Maven Webapp</name>
<url>http://maven.apache.org</url>
<!-- JBoss repository for Hibernate -->
<repositories>
<repository>
<id>JBoss repository</id>
<url>http://repository.jboss.org/nexus/content/groups/public/</url>
</repository>
</repositories>
<properties>
<org.springframework.version>4.2.6.RELEASE</org.springframework.version>
<hibernate.version>4.3.6.Final</hibernate.version>
<servlet.version>3.0.1</servlet.version>
</properties>
<dependencies>
<!-- spring-context which provides core functionality -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!--
https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!-- Hibernate -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<!-- mvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.2.2</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<!-- Tag libs support for view layer -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
<scope>runtime</scope>
</dependency>
</dependencies>
<build>
<finalName>SpringPractice</finalName>
</build>
</project>
2. Create
Alien class with following attributes.
package com.ma3.Entity;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class Alien implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String fullName;
private Date createTime;
private Date updateTime;
public Alien() {
}
public Alien(int id, String fullName, Date createTime, Date updateTime) {
this.id = id;
this.fullName = fullName;
this.createTime = createTime;
this.updateTime = updateTime;
}
/**
* @return the updateTime
*/
public Date getUpdateTime() {
return updateTime;
}
/**
* @param updateTime the updateTime to set
*/
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((createTime == null) ? 0 : createTime.hashCode());
result = prime * result + ((updateTime == null) ? 0 : updateTime.hashCode());
result = prime * result + ((fullName == null) ? 0 : fullName.hashCode());
result = prime * result + id;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
Alien other = (Alien) obj;
if (createTime == null) {
if (other.createTime != null) {
return false;
}
} else if (!createTime.equals(other.createTime)) {
return false;
}
if (fullName == null) {
if (other.fullName != null) {
return false;
}
} else if (!fullName.equals(other.fullName)) {
return false;
}
if (id != other.id) {
return false;
}
return true;
}
@Override
public String toString() {
return "Alien
[id=" + id + ", fullName=" + fullName + ",
createTime=" + createTime + ", updateTime="
+ updateTime + "]";
}
}
3. Create an interface with the name as AlienDao.
package com.ma3.Dao;
import java.util.List;
import com.ma3.Entity.Alien;
public interface AlienDao {
public
Alien createAlien(Alien a);
public
Alien findByName(String name);
public List<Alien> findByFullName(String name);
public Alien findAlienById(int id);
public void updateAlien(Alien id);
public void deleteAlienById(int id);
public List<Alien> getAllAlien();
}
4.Now create
named-queries.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<query name="findByFullName">
<![CDATA[select a from Alien a where
a.fullName = :name]]>
</query>
<query name="findAlienById">
<![CDATA[select a from Alien a where a.id =
:id]]>
</query>
<query name="getAllAlien">
<![CDATA[select a from Alien a]]>
</query>
</hibernate-mapping>
5. Create
AlienDaoImpl.java
package com.ma3.AlienDaoImpl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import
org.springframework.orm.hibernate4.HibernateTemplate;
import
org.springframework.stereotype.Repository;
import
org.springframework.transaction.annotation.Transactional;
import com.ma3.Dao.AlienDao;
import com.ma3.Entity.Alien;
@Transactional(readOnly = false)
@Repository
public class AlienDaoImpl implements AlienDao {
@Autowired
HibernateTemplate template;
public Alien createAlien(Alien a) {
this.template.persist(a);
Alien createdAlien = findAlienById(a.getId());
return createdAlien;
}
public Alien findByName(String name) {
return (Alien) template.findByNamedQueryAndNamedParam("findByFullName", "name", name);
}
@SuppressWarnings("unchecked")
public List<Alien>
findByFullName(String name) {
return (List<Alien>) template.findByNamedQueryAndNamedParam("findByFullName", "name", name);
}
@SuppressWarnings("unchecked")
public Alien findAlienById(int id) {
List<Alien> list = (List<Alien>) template.findByNamedQueryAndNamedParam("findAlienById", "id", id);
Alien alien = new Alien();
for (Alien a : list) {
if (a.getId() == id) {
alien = a;
break;
}
}
return alien;
}
@SuppressWarnings("unchecked")
public List<Alien> getAllAlien() {
return (List<Alien>) template.findByNamedQueryAndValueBean("getAllAlien", new Alien());
}
public void updateAlien(Alien a) {
this.template.update(a);
}
public void deleteAlienById(int id) {
Alien alien = findAlienById(id);
this.template.delete(alien);
}
}
6. Now
create DaoManager.java
package com.ma3.DaoManagers;
import org.springframework.beans.factory.annotation.Autowired;
import
org.springframework.beans.factory.annotation.Qualifier;
import
org.springframework.stereotype.Component;
import com.ma3.Dao.AlienDao;
@Component
public class DaoManager {
@Autowired
@Qualifier("alienDaoImpl")
AlienDao dao;
public AlienDao getAlienDao() {
return dao;
}
}
7. Now
create AlienManager.java interface with following methods.
package com.ma3.Services;
import java.util.List;
import com.ma3.Entity.Alien;
public interface AlienManager {
public Alien createAlien(Alien a);
public void findByName();
public List<Alien> findByFullName(String name);
public Alien
findAlienById(int id);
public void
updateAlienById(Alien a);
public void
deleteAlienById(int id);
public List<Alien> getAllAlien();
}
8. Now create AlienService.java which implements AlienManager.java interface.
package com.ma3.Services;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ma3.DaoManagers.DaoManager;
import com.ma3.Entity.Alien;
@Service
public class AlienService implements AlienManager {
@Autowired
DaoManager
daoMgr;
public Alien createAlien(Alien a) {
a.setCreateTime(new
Date());
a.setUpdateTime(new
Date());
return
daoMgr.getAlienDao().createAlien(a);
}
public void findByName() {
//
TODO Auto-generated method stub
}
public void updateAlienById(Alien a) {
Alien
alien = daoMgr.getAlienDao().findAlienById(a.getId());
a.setCreateTime(alien.getCreateTime());
a.setUpdateTime(new
Date());
daoMgr.getAlienDao().updateAlien(a);
}
public List<Alien> findByFullName(String name) {
//
TODO Auto-generated method stub
return
null;
}
public Alien findAlienById(int id) {
//
TODO Auto-generated method stub
return
daoMgr.getAlienDao().findAlienById(id);
}
public void deleteAlienById(int id) {
daoMgr.getAlienDao().deleteAlienById(id);
}
public List<Alien> getAllAlien() {
//
TODO Auto-generated method stub
List<Alien>
list = daoMgr.getAlienDao().getAllAlien();
return
list;
}
}
9.Now create
create a home.jsp in WEB-INF folder that would be default page of our project.
<html>
<body><br/><br/><br/>
<center>
<h2>Hello Welcome To Spring MVC Tutorial
With HiberNate</h2>
<a href="addAlien">
<button style="background-color:orangered;height:30px; width:130px;border-radius:3px;">
Start The App
</button>
</a>
</center>
</body>
</html>
10. Now
create a folder views in WEB-INF folder and create the following jsp pages.
10. 1. addAlien.jsp
<%@ taglib uri="http://www.springframework.org/tags/form"
prefix="form"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<h1>Add New Alien</h1>
<form:form method="post" action="save">
<table >
<tr>
<td>Name : </td>
<td><form:input path="fullName" /></td>
</tr>
<tr>
<td> </td>
<td><input type="submit"
value="Save" /></td>
</tr>
</table>
</form:form>
10.2. Now
create displayAlien.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<title>Spring MVC Hello Alien</title>
</head>
<body>
<div>
<h2>New Alien</h2>
<table border="3" width="20%">
<tr>
<th>Id</th>
<th>Name</th>
<th>Create Time</th>
<th>Update Time</th>
<th>Edit</th>
</tr>
<tr>
<td>${aliens.id}</td>
<td>${aliens.fullName}</td>
<td>${aliens.createTime}</td>
<td>${aliens.updateTime}</td>
<td><a href="/SpringPractice/editAlienById/${aliens.id}">Update</a></td>
</tr>
</table>
</div>
</body>
</html>
10.3 . Now
create displayAllAliens.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<title>Spring MVC Hello Alien</title>
</head>
<body>
<div>
<h2>All Aliens</h2>
<table border="3" width="20%">
<tr>
<th>Id</th>
<th>Name</th>
<th>Create Time</th>
<th>Update Time</th>
<th>Edit</th>
</tr>
<c:forEach items="${aliens}"
var="aliens">
<tr>
<td>${aliens.id}</td>
<td>${aliens.fullName}</td>
<td>${aliens.createTime}</td>
<td>${aliens.updateTime}</td>
<td><a href="/SpringPractice/editAlienById/${aliens.id}">Update</a></td>
</tr>
</c:forEach>
</table>
</div>
</body>
</html>
10.4 Now
create editAlienById.jsp
<%@ taglib uri="http://www.springframework.org/tags/form"
prefix="form"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<h1>Update Alien</h1>
<form:form method="POST" action="/SpringPractice/editsave">
<table>
<tr>
<td><form:hidden path="id"
/></td>
</tr>
<tr>
<td>Name :</td>
<td><form:input path="fullName"
/></td>
</tr>
<tr>
<td></td>
<td><input type="submit"
value="Save" /></td>
</tr>
</table>
</form:form>
11. Now
create spring-mvc-servlet.xml (Note : Here spring-mvc is user defined name but -servlet is important).
Note : <mvc:annotation-driven/> is use to enable the Spring MVC components with its default configurations. Even if we don't include <mvc:annotation-driven/> also application would work if you have used the <context:component-scan/> for creating the beans. So i have used <context:component-scan/> instead of <mvc:annotation-driven/> .
Note : <mvc:annotation-driven/> is use to enable the Spring MVC components with its default configurations. Even if we don't include <mvc:annotation-driven/> also application would work if you have used the <context:component-scan/> for creating the beans. So i have used <context:component-scan/> instead of <mvc:annotation-driven/> .
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<tx:annotation-driven transaction-manager="txManager"/>
<context:annotation-config />
<context:component-scan base-package="com.ma3"/>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url"
value="jdbc:mysql://localhost:3306/13july"
/>
<property name="username"
value="root" />
<property name="password"
value="" />
</bean>
<bean id="mySessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="mappingLocations">
<list>
<!-- Named
Query Mapping File -->
<value>WEB-INF/named-queries.hbm.xml</value>
<!--
<value>com/ma3/EntityMapping/alien.hbm.xml</value>
<value>com/ma3/EntityMapping/planet.hbm.xml</value>
-->
</list>
</property>
<property name="annotatedClasses">
<list>
<value>com.ma3.Entity.Alien</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate4.HibernateTemplate">
<property name="sessionFactory" ref="mySessionFactory"></property>
</bean>
<bean id="txManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"
autowire="byType">
<!-- <property
name="sessionFactory" ref="mySessionFactory"></property>
-->
</bean>
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"
/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"
/>
<property name="suffix" value=".jsp"
/>
</bean>
</beans>
12. Configure
web.xml as follows.
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" 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>Archetype Created Web Application</display-name>
<welcome-file-list>
<welcome-file>home.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>spring-mvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring-mvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
13. And
finally create application controller AlienController.java as follows.
package com.ma3.controller;
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.ma3.Entity.Alien;
import com.ma3.Services.AlienService;
@Controller
public class AlienController {
@Autowired
AlienService
service;
@RequestMapping("/addAlien")
public String showform(Model m) {
m.addAttribute("command",
new Alien());
return
"addAlien";
}
@RequestMapping(value
= "/save", method = RequestMethod.POST)
public String save(@ModelAttribute("alien") Alien alien, Model m) {
alien
= service.createAlien(alien);
m.addAttribute("aliens",
alien);
return
"displayAlien";
}
@RequestMapping(value
= "/getAlienById/{id}", method = RequestMethod.GET)
public String getAlienById(@PathVariable int id, Model m) {
m.addAttribute("aliens",
service.findAlienById(id));
return
"displayAlien";
}
@RequestMapping(value
= "/getAllAliens", method = RequestMethod.GET)
public String getAllAliens(Model model) {
model.addAttribute("aliens",
service.getAllAlien());
return
"displayAllAliens";
}
@RequestMapping(value
= "/editAlienById/{id}", method = RequestMethod.GET)
public String editAlienById(@PathVariable int id, Model m) {
Alien
a = service.findAlienById(id);
m.addAttribute("command",
a);
return
"editAlienById";
}
@RequestMapping(value
= "/editsave", method = RequestMethod.POST)
public String editsave(@ModelAttribute("a") Alien a, Model m) {
service.updateAlienById(a);
m.addAttribute("aliens",
service.findAlienById(a.getId()));
return
"displayAlien";
}
@RequestMapping(value
= "/deleteAlienById/{id}", method = RequestMethod.GET)
public String deleteAlienById(@PathVariable int id) {
service.deleteAlienById(id);
return
"displayAllAliens";
}
}
Test the
application, start the tomcat server on 8080, and hit the following URL :
Fill the field and hit the save button, then you will be redirect to http://localhost:8080/SpringPractice/save and similarly add more aliens .
Now you can update the newly create alien by clicking on Update link of Edit column(http://localhost:8080/SpringPractice/editAlienById/7).
You can delete aliens by using its id’s by using this URL : http://localhost:8080/SpringPractice/deleteAlienById/1
Test In Eclipse 2019-
Thanks hope it will help you, GOOD LUCK.
No comments