Step 1: Create a Database DAVDB on MySql Database and also we create Category and Publication tables on this database.
Category Table
CREATE TABLE `category` ( `categoryId` int(11) NOT NULL AUTO_INCREMENT, `categoryName` varchar(255) DEFAULT NULL, PRIMARY KEY (`categoryId`) )
Publication Table
CREATE TABLE `publication` ( `pubId` int(11) NOT NULL AUTO_INCREMENT, `content` varchar(255) DEFAULT NULL, `Title` varchar(255) DEFAULT NULL, `categoryId` int(11) DEFAULT NULL, PRIMARY KEY (`pubId`), KEY `FK23254A0CAF274936` (`categoryId`), CONSTRAINT `FK23254A0CAF274936` FOREIGN KEY (`categoryId`) REFERENCES `category` (`categoryId`) )
Step 2: Create a database.properties for database configuration information in the resources folder under src folder in the created project.
database.driver=com.mysql.jdbc.Driver database.url=jdbc:mysql://localhost:3306/DAVDB database.user=root database.password=root hibernate.dialect=org.hibernate.dialect.MySQLDialect hibernate.show_sql=true hibernate.hbm2ddl.auto=create
Step 3: Create a Dynamic Web Project with a name elhumeante and create packages com.dineshonjava.controller, com.dineshonjava.bean, com.dineshonjava.dao, com.dineshonjava.service, com.dineshonjava.model under the src folder in the created project.
Step 4: Add below mentioned Spring 3.0 and Hibernate 3.0 related libraries and other libraries into the folder WebRoot/WEB-INF/lib.
Step 5: Create a Java class CategoryController, PublicationController, CategoryBean, PublicationBean, CategoryDao, CategoryDaoImpl, PublicationDao, PublicationDaoImpl, CategoryService, CategoryServiceImpl, PublicationService, PublicationServiceImpl under the respective packages..
Step 6: Create Spring configuration files web.xml and sdnext-servlet.xml under the WebRoot/WEB-INF/ and WebRoot/WEB-INF/config folders.
Step 7: Create a sub-folder with a name views under the WebRoot/WEB-INF folder. Create a view file addCategory.jsp and addPublication.jsp under this sub-folder.
Step 8: The final step is to create the content of all the source and configuration files name sdnext-servlet.xml under the sub-folder /WebRoot/WEB-INF/config and export the application as explained below.
Application Architecture
We will have a layered architecture for our demo application. The database will be accessed by a Data Access layer popularly called as DAO Layer(CategoryDao, PublicationDao). This layer will use Hibernate API to interact with database. The DAO layer will be invoked by a service layer. In our application we will have a Service interface called CategoryService, PublicationService.
CategoryBean.java
package com.dineshonjava.bean; 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="Category") public class CategoryBean { @Id @Column(name="categoryId") @GeneratedValue(strategy=GenerationType.AUTO) private Integer categoryId; @Column(name="categoryName") private String categoryName; public Integer getCategoryId() { return categoryId; } public void setCategoryId(Integer categoryId) { this.categoryId = categoryId; } public String getCategoryName() { return categoryName; } public void setCategoryName(String categoryName) { this.categoryName = categoryName; } }
PublicationBean.java
package com.dineshonjava.bean; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.OneToOne; import javax.persistence.Table; @Entity @Table(name="Publication") public class PublicationBean implements Serializable{ private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy=GenerationType.AUTO) @Column(name = "pubId") private Integer pubId; @Column(name="Title") private String pubTitle; @OneToOne @JoinColumn(name="categoryId") private CategoryBean category; @Column(name="content") private String pubContent; public Integer getPubId() { return pubId; } public void setPubId(Integer pubId) { this.pubId = pubId; } public String getPubTitle() { return pubTitle; } public void setPubTitle(String pubTitle) { this.pubTitle = pubTitle; } public String getPubContent() { return pubContent; } public CategoryBean getCategory() { return category; } public void setCategory(CategoryBean category) { this.category = category; } public void setPubContent(String pubContent) { this.pubContent = pubContent; } }
CategoryDao.java
package com.dineshonjava.dao; import java.util.List; import com.dineshonjava.bean.CategoryBean; public interface CategoryDao { public void addCategory(CategoryBean categoryBean); public List<CategoryBean> getCategories(); public CategoryBean getCategory(int categoryId); public void deleteCategory(int categoryId); }
PublicationDao.java
package com.dineshonjava.dao; import java.util.List; import com.dineshonjava.bean.PublicationBean; public interface PublicationDao { public void addPublication(PublicationBean publicationBean); public List<PublicationBean> getPublications(); public PublicationBean getPublication(int pubId); public void deletePublication(int pubId); }
CategoryDaoImpl.java
package com.dineshonjava.dao; import java.util.List; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import com.dineshonjava.bean.CategoryBean; /** * @author Dinesh Rajput * */ @Repository("categoryDao") public class CategoryDaoImpl implements CategoryDao { @Autowired private SessionFactory sessionFactory; @Override public void addCategory(CategoryBean categoryBean) { sessionFactory.getCurrentSession().saveOrUpdate(categoryBean); } @SuppressWarnings("unchecked") @Override public List<CategoryBean> getCategories() { return (List<CategoryBean>) sessionFactory.getCurrentSession().createCriteria(CategoryBean.class).list(); } @Override public CategoryBean getCategory(int categoryId) { return (CategoryBean) sessionFactory.getCurrentSession().get(CategoryBean.class, categoryId); } @Override public void deleteCategory(int categoryId) { sessionFactory.getCurrentSession().createQuery("DELETE FROM category WHERE categoryId = "+categoryId).executeUpdate(); } }
PublicationDaoImpl.java
package com.dineshonjava.dao; import java.util.List; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import com.dineshonjava.bean.PublicationBean; /** * @author Dinesh Rajput * */ @Repository("publicationDao") public class PublicationDaoImpl implements PublicationDao { @Autowired private SessionFactory sessionFactory; public void addPublication(PublicationBean publicationBean) { sessionFactory.getCurrentSession().saveOrUpdate(publicationBean); } @SuppressWarnings("unchecked") @Override public List<PublicationBean> getPublications() { return (List<PublicationBean>) sessionFactory.getCurrentSession().createCriteria(PublicationBean.class).list(); } @Override public PublicationBean getPublication(int pubId) { return (PublicationBean) sessionFactory.getCurrentSession().get(PublicationBean.class, pubId); } @Override public void deletePublication(int pubId) { sessionFactory.getCurrentSession().createQuery("DELETE FROM Publication WHERE pubId = "+pubId).executeUpdate(); } }
CategoryService.java
package com.dineshonjava.service; import java.util.List; import com.dineshonjava.bean.CategoryBean; public interface CategoryService { public void addCategory(CategoryBean categoryBean); public List<CategoryBean> getCategories(); public CategoryBean getCategory(int categoryId); public void deleteCategory(int categoryId); }
CategoryServiceImpl.java
package com.dineshonjava.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import com.dineshonjava.bean.CategoryBean; import com.dineshonjava.dao.CategoryDao; /** * @author Dinesh Rajput * */ @Service("categoryService") @Transactional(propagation = Propagation.SUPPORTS, readOnly = true) public class CategoryServiceImpl implements CategoryService { @Autowired private CategoryDao categoryDao; @Transactional(propagation = Propagation.REQUIRED, readOnly = false) public void addCategory(CategoryBean categoryBean) { categoryDao.addCategory(categoryBean); } @Override public List<CategoryBean> getCategories() { return categoryDao.getCategories(); } @Override public CategoryBean getCategory(int categoryId) { return categoryDao.getCategory(categoryId); } @Override public void deleteCategory(int categoryId) { categoryDao.deleteCategory(categoryId); } }
PublicationService.java
package com.dineshonjava.service; import java.util.List; import com.dineshonjava.bean.PublicationBean; public interface PublicationService { public void addPublication(PublicationBean publicationBean); public List<PublicationBean> getPublications(); public PublicationBean getPublication(int pubId); public void deletePublication(int pubId); }
PublicationServiceImpl.java
package com.dineshonjava.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import com.dineshonjava.bean.PublicationBean; import com.dineshonjava.dao.PublicationDao; /** * @author Dinesh Rajput * */ @Service("publicationService") @Transactional(propagation = Propagation.SUPPORTS, readOnly = true) public class PublicationServiceImpl implements PublicationService { @Autowired private PublicationDao publicationDao; @Transactional(propagation = Propagation.REQUIRED, readOnly = false) public void addPublication(PublicationBean publicationBean) { publicationDao.addPublication(publicationBean); } public List<PublicationBean> getPublications() { return publicationDao.getPublications(); } @Override public PublicationBean getPublication(int pubId) { return publicationDao.getPublication(pubId); } @Override public void deletePublication(int pubId) { publicationDao.deletePublication(pubId); } }
CategoryController.java
package com.dineshonjava.controller; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; 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.RequestMethod; import org.springframework.web.servlet.ModelAndView; import com.dineshonjava.bean.CategoryBean; import com.dineshonjava.service.CategoryService; /** * @author Dinesh Rajput * */ @Controller public class CategoryController { @Autowired private CategoryService categoryService; @RequestMapping(value = "/saveCategory", method = RequestMethod.POST) public ModelAndView saveEmployee(@ModelAttribute("command") CategoryBean category, BindingResult result) { categoryService.addCategory(category); return new ModelAndView("redirect:/addCategory.html"); } @RequestMapping(value = "/addCategory", method = RequestMethod.GET) public ModelAndView addCategory(@ModelAttribute("command") CategoryBean category, BindingResult result) { Map<String, Object> model = new HashMap<String, Object>(); model.put("categories", categoryService.getCategories()); return new ModelAndView("addCategory", model); } @RequestMapping(value = "/deleteCategory", method = RequestMethod.GET) public ModelAndView deleteCategory(@ModelAttribute("command") CategoryBean category, BindingResult result) { categoryService.deleteCategory(category.getCategoryId()); Map<String, Object> model = new HashMap<String, Object>(); model.put("categories", categoryService.getCategories()); return new ModelAndView("addCategory", model); } @RequestMapping(value = "/editCategory", method = RequestMethod.GET) public ModelAndView editCategory(@ModelAttribute("command") CategoryBean category, BindingResult result) { Map<String, Object> model = new HashMap<String, Object>(); model.put("category", categoryService.getCategory(category.getCategoryId())); model.put("categories", categoryService.getCategories()); return new ModelAndView("addCategory", model); } @RequestMapping(value="/categories", method = RequestMethod.GET) public List<CategoryBean> getCategories() { return categoryService.getCategories(); } }
PublicationController.java
package com.dineshonjava.controller; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; 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.RequestMethod; import org.springframework.web.servlet.ModelAndView; import com.dineshonjava.bean.PublicationBean; import com.dineshonjava.service.CategoryService; import com.dineshonjava.service.PublicationService; @Controller public class PublicationController { @Autowired private PublicationService publicationService; @Autowired private CategoryService categoryService; @RequestMapping(value = "/savePublication", method = RequestMethod.POST) public ModelAndView saveEmployee(@ModelAttribute("command") PublicationBean publication, BindingResult result) { publicationService.addPublication(publication); return new ModelAndView("redirect:/addPublication.html"); } @RequestMapping(value = "/addPublication", method = RequestMethod.GET) public ModelAndView addPublication(@ModelAttribute("command") PublicationBean publication, BindingResult result) { Map<String, Object> model = new HashMap<String, Object>(); model.put("publications", publicationService.getPublications()); model.put("categories", categoryService.getCategories()); return new ModelAndView("addPublication", model); } @RequestMapping(value = "/deletePublication", method = RequestMethod.GET) public ModelAndView deletePublication(@ModelAttribute("command") PublicationBean publication, BindingResult result) { publicationService.deletePublication(publication.getPubId()); Map<String, Object> model = new HashMap<String, Object>(); model.put("publications", publicationService.getPublications()); model.put("categories", categoryService.getCategories()); return new ModelAndView("addPublication", model); } @RequestMapping(value = "/editPublication", method = RequestMethod.GET) public ModelAndView editPublication(@ModelAttribute("command") PublicationBean publication, BindingResult result) { Map<String, Object> model = new HashMap<String, Object>(); model.put("publication", publicationService.getPublication(publication.getPubId())); model.put("publications", publicationService.getPublications()); model.put("categories", categoryService.getCategories()); return new ModelAndView("addPublication", model); } @RequestMapping(value="/publications", method = RequestMethod.GET) public List<PublicationBean> getPublications() { return publicationService.getPublications(); } }
Spring Web configuration file web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" 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_2_5.xsd"> <servlet> <servlet-name>sdnext</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/config/sdnext-servlet.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>sdnext</servlet-name> <url-pattern>*.html</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file> addCategory.html </welcome-file> </welcome-file-list> </web-app>
Spring Web configuration file sdnext-servlet.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"> <context:property-placeholder location="classpath:resources/database.properties" /> <context:component-scan base-package="com.dineshonjava" /> <tx:annotation-driven transaction-manager="hibernateTransactionManager"/> <bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /> <property name="prefix" value="/WEB-INF/view/" /> <property name="suffix" value=".jsp" /> </bean> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="${database.driver}" /> <property name="url" value="${database.url}" /> <property name="username" value="${database.user}" /> <property name="password" value="${database.password}" /> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="annotatedClasses"> <list> <value>com.dineshonjava.bean.CategoryBean</value> <value>com.dineshonjava.bean.PublicationBean</value> </list> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">${hibernate.dialect}</prop> <prop key="hibernate.show_sql">${hibernate.show_sql}</prop> <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop> </props> </property> </bean> <bean id="hibernateTransactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean> </beans>
addCategory.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"%> <%@ 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"> <title>Spring MVC Form Handling</title> </head> <body><center> <h2>Create New Category</h2> <form:form method="POST" action="/elhumeante/saveCategory.html"> <table> <tr> <td><form:label path="categoryId">Category ID:</form:label></td> <td><form:input path="categoryId" readonly="true"/></td> </tr> <tr> <td><form:label path="categoryName">Category Name:</form:label></td> <td><form:input path="categoryName" value="${category.categoryName}"/></td> </tr> <tr> <tr> <td> </td> <td><input type="submit" value="SAVE"/></td> </tr> </table> </form:form> <br/> <c:if test="${!empty categories}"> <table align="center" border="1"> <tr> <th>Category ID</th> <th>Category Name</th> <th>Options</th> </tr> <c:forEach items="${categories}" var="category"> <tr> <td><c:out value="${category.categoryId}"/></td> <td><c:out value="${category.categoryName}"/></td> <td align="center"><a href="editCategory.html?categoryId=${category.categoryId}">Edit</a> | <a href="deleteCategory.html?categoryId=${category.categoryId}">Delete</a></td> </tr> </c:forEach> </table> </c:if> <h2><a href="addPublication.html">Adding Publication</a></h2> </center> </body> </html>
addPublication.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"%> <%@ 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"> <title>Spring MVC Form Handling</title> </head> <body> <center> <h2>Create New Publication</h2> <form:form method="POST" action="/elhumeante/savePublication.html"> <table> <tr> <td><form:label path="pubId">Publication ID:</form:label></td> <td><form:input path="pubId" value="${publication.pubId}" readonly="true"/></td> </tr> <tr> <td><form:label path="pubTitle">Publication Title:</form:label></td> <td><form:input path="pubTitle" value="${publication.pubTitle}"/></td> </tr> <tr> <td> <form:label path="category.categoryId">Publication Type:</form:label> </td> <td> <form:select path="category.categoryId" cssStyle="width: 150px;"> <option value="-1">Select a type</option> <c:forEach items="${categories}" var="category"> <option value="${category.categoryId}">${category.categoryName}</option> </c:forEach> </form:select> </td> </tr> <tr> <td><form:label path="pubContent">Publication Content:</form:label></td> <td><form:textarea path="pubContent" value="${publication.pubContent}" cssStyle="width: 150px;"/></td> </tr> <tr> <td> </td> <td><input type="submit" value="SAVE"/></td> </tr> </table> </form:form> <br/> <c:if test="${!empty publications}"> <table align="center" border="1"> <tr> <th>ID</th> <th>Title</th> <th>Type</th> <th>Content</th> <th>Options</th> </tr> <c:forEach items="${publications}" var="publication"> <tr> <td><c:out value="${publication.pubId}"/></td> <td><c:out value="${publication.pubTitle}"/></td> <td><c:out value="${publication.category.categoryName}"/></td> <td><c:out value="${publication.pubContent}"/></td> <td align="center"><a href="editPublication.html?pubId=${publication.pubId}">Edit</a> | <a href="deletePublication.html?pubId=${publication.pubId}">Delete</a></td> </tr> </c:forEach> </table> </c:if> <h2><a href="addCategory.html">Adding Category</a></h2> </center> </body> </html>
Once you are done with creating source and configuration files, export your application. Right click on your application and use Export-> WAR File option and save your elhumeante.war file in Tomcat’s webapps folder.
Now start your Tomcat server and make sure you are able to access other web pages from webapps folder using a standard browser. Now try a URL http://localhost:8181/elhumeante/ and you should see the following result if everything is fine with your Spring Web Application:
Create category:
Create Publication:
Download Source code
elhumeante.zip
- Spring MVC Web Tutorial
- Spring MVC Interview Questions
- MVC Design Pattern
- Spring MVC DispatcherServlet
- Spring MVC WebApplicationContext and Root Application Context
- Spring MVC @Controller Annotation
- Spring MVC @RequestMapping Annotation
- Spring MVC @RequestParam Annotation
- Spring MVC ContextLoaderListener
- Spring MVC @RequestParam and @PathVariable annotations
- Spring MVC Hello World Example
- Spring MVC Exception Handling Example
- Spring MVC with Hibernate CRUD Example
- Spring MVC Tiles Plugin with Example
- Spring MVC Interceptor with example
- Spring MVC with MongoDB CRUD Example
- Spring MVC Internationalization & Localization with Example
1
Hi Dinesh Rajput ,
You are taking one-To-One Relationship with category and publication…….bt here its goes to one-To-many y bcz a parent table category contains more than one record in corresponding child table publication…..please check it once and give me Clarification.
Thank you dinesh.
Dinesh On Java
Hi friend,
Please look once again this example here I have described two tables (Publication and Category) every publication record have one category Id for example "Hibernate & Spring" publication has category "Technology" category i.e. Publication table map one to one with category table.
Regards,
Dinesh On Java
Hi Dinesh Rajput ,
You are taking one-To-One Relationship with category and publication…….
but in this example delete operation not working.please check and reply it.
Hi Satya Prakash Verma,
Lets we check after modify we will confirmed you.
Thanks,
Anamika
hello… wen i imported this application and tried working i got this error…. can anyone help me please
HTTP Status 404 – /saveCategory.html
——————————————————————————–
type Status report
message /saveCategory.html
description The requested resource is not available.
——————————————————————————–
Apache Tomcat/7.0.42
can u please help me to list the contents in order??? its not in an order now….
In the form action you 've to change (
In DaoImpl of both Category and Publications the deleteCategory/Publictions functionality you 've to change…because both are associated with categoryId…To perform delete in category you need to "delete from publication where categoryId=?" First and in Publication also….
it worked…. Idont know how to share it…but i'lll soooon……..
using spring mvc and hibernate how can i add and release the person. for example
there is parking. first check whether the slot is their r not. then add the person to this slot and same we need release the parking slot. please guide me sir. thank you
I am getting this error—HTTP Status 404 – /elhumeante/savePublication.html.
Where is savePublication.html page ?
hello… wen i imported this application and tried working i got this error…. can anyone help me please
HTTP Status 404 – /saveCategory.html
all work fine but when i click on edit link on publication.html page then all field of value is display in text box but when i click on save button then it cannot to be update and normal insert working fine.
can yo help me please……………….
hi Dinesh,
when i click on edit button all field of publication is shown in to text box but category is not selected automatically. can you tell me how it work ? I will facing a problem with that.
THAT IS NOT PAGE THAT IS URL WHICH IS AVAILABLE IN CONTROLLER