SpringMVC3 Hibernate CRUD Sample Application

To learn any web framework starting with a HelloWorld application is a good idea. Once we get familiarity with the framework configuration it would be better to do a CRUD(Create,Read,Update,Delete) application which covers various aspects of a web framework like Validations, Request URL Mappings, Request Parameter Binding,
Pre-populating forms etc.

Now I am going to explain how to write a Simple CRUD application using SpringMVC3, Hibernate and MySQL.
Our Application is ContactsManagements where you can view or search contacts, create new contacts, edit or delete existing contacts.

Step#1: Create the CONTACTS Table

CREATE TABLE  CONTACTS 
(
id int(10) unsigned NOT NULL AUTO_INCREMENT,
name varchar(45) NOT NULL,
address varchar(45) DEFAULT NULL,
gender char(1) DEFAULT 'M',
dob datetime DEFAULT NULL,
email varchar(45) DEFAULT NULL,
mobile varchar(15) DEFAULT NULL,
phone varchar(15) DEFAULT NULL,
PRIMARY KEY (id)
);

Step#2: Copy the SpringMVC, Hibernate and their dependent jars into WEB-INF/lib folder.
If you are using Maven you can mention the following dependencies.



junit
junit
4.8.1
jar
compile


org.springframework
spring-web
3.0.5.RELEASE
jar
compile


org.springframework
spring-core
3.0.5.RELEASE
jar
compile


commons-logging
commons-logging




log4j
log4j
1.2.14
jar
compile


org.springframework
spring-tx
3.0.5.RELEASE
jar
compile


jstl
jstl
1.1.2
jar
compile


taglibs
standard
1.1.2
jar
compile


org.springframework
spring-webmvc
3.0.5.RELEASE
jar
compile


org.springframework
spring-aop
3.0.5.RELEASE
jar
compile


commons-digester
commons-digester
2.1
jar
compile


commons-collections
commons-collections
3.2.1
jar
compile


org.hibernate
hibernate-core
3.3.2.GA
jar
compile


javax.persistence
persistence-api
1.0
jar
compile


c3p0
c3p0
0.9.1.2
jar
compile


org.springframework
spring-orm
3.0.5.RELEASE
jar
compile


org.slf4j
slf4j-api
1.6.1
jar
compile


org.slf4j
slf4j-log4j12
1.6.1
jar
compile


cglib
cglib-nodep
2.2
jar
compile


org.hibernate
hibernate-annotations
3.4.0.GA
jar
compile


jboss
javassist
3.7.ga
jar
compile


mysql
mysql-connector-java
5.1.14
jar
compile


Step#3: Configure SpringMVC

a) Configure DispatcherServlet in web.xml


dispatcher
org.springframework.web.servlet.DispatcherServlet
1



dispatcher
*.do



org.springframework.web.context.ContextLoaderListener


contextConfigLocationclasspath:applicationContext.xml

b) Configure View Resolver in WEB-INF/dispatcher-servlet.xml



c) Configure Annotation support, PropertyPlaceHolderConfigurer, ResourceBundleMessageSource in WEB-INF/classes/applicationContext.xml











Step#4: Configure JDBC connection parameters and Hibernate properties in config.properties

################### JDBC Configuration ##########################
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/sivalabs
jdbc.username=root
jdbc.password=admin

################### Hibernate Configuration ##########################
hibernate.dialect=org.hibernate.dialect.MySQLDialect
hibernate.show_sql=true
#hibernate.hbm2ddl.auto=update
hibernate.generate_statistics=true

Step#5: Configure DataSource, SessionFactory, TransactionManagement support in WEB-INF/classes/applicationContext.xml








${hibernate.dialect}
${hibernate.show_sql}










Step#6: Configure the Labels, error messages in WEB-INF/classes/Messages.properties

App.Title=SivaLabs
typeMismatch.java.util.Date={0} is Invalid Date.
dob=DOB

Step#7: Create the Entity class Contact.java

package com.sivalabs.contacts;

import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

import org.apache.commons.lang.builder.ToStringBuilder;

@Entity
@Table(name="CONTACTS")
public class Contact
{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
@Column private String name;
@Column private String address;
@Column private String gender;
@Column private Date dob;
@Column private String email;
@Column private String mobile;
@Column private String phone;

@Override
public String toString()
{
return ToStringBuilder.reflectionToString(this);
}
//setters & getters
}

Step#8: Create the ContactsDAO.java which performs CRUD operations on CONTACTS table.

package com.sivalabs.contacts;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

@Repository
@Transactional
public class ContactsDAO
{
@Autowired
private SessionFactory sessionFactory;

public Contact getById(int id)
{
return (Contact) sessionFactory.getCurrentSession().get(Contact.class, id);
}

@SuppressWarnings("unchecked")
public List<Contact> searchContacts(String name)
{
Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Contact.class);
criteria.add(Restrictions.ilike("name", name+"%"));
return criteria.list();
}

@SuppressWarnings("unchecked")
public List<Contact> getAllContacts()
{
Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Contact.class);
return criteria.list();
}

public int save(Contact contact)
{
return (Integer) sessionFactory.getCurrentSession().save(contact);
}

public void update(Contact contact)
{
sessionFactory.getCurrentSession().merge(contact);
}

public void delete(int id)
{
Contact c = getById(id);
sessionFactory.getCurrentSession().delete(c);
}
}

Step#9: Create ContactFormValidator.java which performs the validations on saving/updating a contact.

package com.sivalabs.contacts;

import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

@Component("contactFormValidator")
public class ContactFormValidator implements Validator
{
@SuppressWarnings("unchecked")
@Override
public boolean supports(Class clazz)
{
return Contact.class.isAssignableFrom(clazz);
}

@Override
public void validate(Object model, Errors errors)
{
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name","required.name", "Name is required.");
}
}

Step#10: Create ContactsControllers.java which processes all the CRUD requests.

package com.sivalabs.contacts;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
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.bind.annotation.RequestParam;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class ContactsControllers
{
@Autowired
private ContactsDAO contactsDAO;

@Autowired
private ContactFormValidator validator;

@InitBinder
public void initBinder(WebDataBinder binder)
{
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
dateFormat.setLenient(false);
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
}

@RequestMapping("/searchContacts")
public ModelAndView searchContacts(@RequestParam(required= false, defaultValue="") String name)
{
ModelAndView mav = new ModelAndView("showContacts");
List<Contact> contacts = contactsDAO.searchContacts(name.trim());
mav.addObject("SEARCH_CONTACTS_RESULTS_KEY", contacts);
return mav;
}

@RequestMapping("/viewAllContacts")
public ModelAndView getAllContacts()
{
ModelAndView mav = new ModelAndView("showContacts");
List<Contact> contacts = contactsDAO.getAllContacts();
mav.addObject("SEARCH_CONTACTS_RESULTS_KEY", contacts);
return mav;
}

@RequestMapping(value="/saveContact", method=RequestMethod.GET)
public ModelAndView newuserForm()
{
ModelAndView mav = new ModelAndView("newContact");
Contact contact = new Contact();
mav.getModelMap().put("newContact", contact);
return mav;
}

@RequestMapping(value="/saveContact", method=RequestMethod.POST)
public String create(@ModelAttribute("newContact")Contact contact, BindingResult result, SessionStatus status)
{
validator.validate(contact, result);
if (result.hasErrors())
{
return "newContact";
}
contactsDAO.save(contact);
status.setComplete();
return "redirect:viewAllContacts.do";
}

@RequestMapping(value="/updateContact", method=RequestMethod.GET)
public ModelAndView edit(@RequestParam("id")Integer id)
{
ModelAndView mav = new ModelAndView("editContact");
Contact contact = contactsDAO.getById(id);
mav.addObject("editContact", contact);
return mav;
}

@RequestMapping(value="/updateContact", method=RequestMethod.POST)
public String update(@ModelAttribute("editContact") Contact contact, BindingResult result, SessionStatus status)
{
validator.validate(contact, result);
if (result.hasErrors()) {
return "editContact";
}
contactsDAO.update(contact);
status.setComplete();
return "redirect:viewAllContacts.do";
}

@RequestMapping("deleteContact")
public ModelAndView delete(@RequestParam("id")Integer id)
{
ModelAndView mav = new ModelAndView("redirect:viewAllContacts.do");
contactsDAO.delete(id);
return mav;
}
}

Step#11: Instead of writing the JSTL tag library declerations in all the JSPs, declare them in one JSP and include that JSP in other JSPs.
taglib_includes.jsp

<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>

<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>

Step#12: Create the JSPs.

a)showContacts.jsp

<%@include file="taglib_includes.jsp" %>

<html>
<head>

<title> </title>

</head>
<body style="font-family: Arial; font-size:smaller;">



Enter Contact Name

  

  






Id Name Address Mobile
No Results found


 Edit

  Delete


</body>
</html>

b)newContact.jsp

<%@include file="taglib_includes.jsp" %>

<html>
<head>

<title> </title>
</head>
<body style="font-family: Arial; font-size:smaller;">




Edit Contact Form











Name



DOB
Gender

Address

Email
Mobile





 



 

</body>
</html>

a)editContact.jsp

<%@include file="taglib_includes.jsp" %>

<html>
<head>

<title> </title>
</head>
<body style="font-family: Arial; font-size:smaller;">




Edit Contact Form












Id



Name



DOB
Gender

Address

Email
Mobile





 



 

</body>
</html>

Step#13: Write the javascript file js/contacts.js containing the utility methods

function go(url)
{
window.location = url;
}

function deleteContact(url)
{
var isOK = confirm("Are you sure to delete?");
if(isOK)
{
go(url);
}
}

Step#14: The welcome file index.jsp

<%
response.sendRedirect("viewAllContacts.do");
%>

Step#15: Start the server and point your browser URL to http://localhost:8080/SpringMVCHibernate

You can download the source code at
SpringMVCHibernate.zip

115 thoughts on “SpringMVC3 Hibernate CRUD Sample Application”

  1. Ou… A lot of work, a lot of files, another table – a lot of boilerplate code.

    If you are a beginner – you don't have a lot of fun?

  2. Hi Siva, This is a very nice article. Is it possible to upload all the source as a zip file? Thanks in advance.

  3. Hi AndreAgosto,

    Here I covered
    a) Configuration of SpringMVC Controller, View Resolver, PropertyPlaceHolder, MessageResource Bundle
    b) How to use Annotations for Form (GET/POST) processing
    c) How to perform Validations
    d) How to customize and show user friendly validation message
    e) Hibernate integration using Annotation based approach
    and few more things.

    So this tutorial might be exhaustive for you. Take it slowly ๐Ÿ™‚

    ModelAndView is Spring framework's class(org.springframework.web.servlet.ModelAndView) which represent a logical view and holds the data that we want to display in that view.

    For example, If we want to display a welcome.jsp which is in /WEB-INF/jsp/ folder we can build a ModelAndView object and give it to Spring Controller as follows:

    MoadelAndView mav = new ModelAndView("welcome");
    return mav;

    Spring framework will resolve this to a physical JSP page using ViewResolver configuration in dispatcher-servlet.xml.

    Thanks,
    Siva

  4. Newbie here. May i know what files i need to change in order to let it run on postgresql instead of mysql. Thanks.

  5. Hi,
    To use different database you just need to change jdbc properties in config.properties mentioned in Step#4.

    Set JDBC paramters specifi to postgresql and change the Hibernate dialect to Postgres. thats it.

  6. Hi,

    Great tutorial !
    I want to perform some tests by running the application as a Java application and not a web application.
    In a main function I have made the initialisation of the Spring context like this :

    ClassPathXmlApplicationContext appContext = null;
    try {
    appContext = new ClassPathXmlApplicationContext(
    new String[] {"applicationContext.xml"});
    } catch(Exception ex) {
    ex.printStackTrace();
    }

    But how to get the sessionFactory and contactsDAO after that ?
    I would like to use the contactsDAO like this in my Test class : contactsDAO.save(new Contact(….));

  7. Hi,
    Once you get the appContext object you can get ContactsDAO as follows:
    ContactsDAO contactsDAO = (ContactsDAO)appContext.getBean("contactsDAO");

  8. Hi Siva,

    Thanks so much for the example !!
    Can you please provide the steps like how i need to make this run in IntelliJ IDEA 10.

    Thanks,
    Krishna

  9. I want this project to run on IntelliJ IDEA 10.
    As i am new to this i am facing some problems,can you please help me out.

    Thanks,
    Krishna

  10. Excellent article, Siva. I'd like to know your opinion on play framework or some other agile web framework, I guess that ease of use must come at a cost… so I'd like to know the pros / cons of using those framework or going with the sping approach…

  11. Hi,
    While writing this CRUD application I checked out if there is any existing frameworks suitable for CRUD kind of applications. I found OpenXava, Play, Stripes etc are really good and simple for CRUD.

    But in my opinion writing a CRUD application is only to get familiarity with the frameworks.
    I think enterprise applications which involves only CRUD operations are not that straight forward. There will be very complex business rules, presentation based on client types etc…

    Many frameworks just looks great while doing simple POCs but while doing real things we actually realise the limitations of those frameworks.

    First thing we should consider while choosing a framework is to understand what kind of application we are going to develop. Is it a RIA application with jazzy UI or is it back-end
    processing system with less UI interaction. Then pick the frameworks which are providing the support for our major requirement.

    Same time we should not ignore these framework because of lack of their popularity.

    I will take a look at Play and will provide my opinion on Play soon.

    Keep watching my blog ๐Ÿ™‚

    Thanks,
    Siva

  12. Hi Siva,

    Thanks for the article,my query may sound silly but me being new to this can you clear my doubts,I need add other controller how to map that for ex say add datas to other table employee how to do this and map the controller.

    thanks,

    Joshua Daniel

  13. Hi,
    1. Create a jsp new_emaployee.jsp to display new employee form and submit the form to createEmployee.do

    2. Create a Controller and map the url to createEmployee.do using @RequestMapping as follows:

    @Controller
    public class EmployeeController
    {
    @RequestMapping("/createEmployee")
    public ModelAndView create(Employee emp)
    {
    // invoke DAO and Save new Emp to Database
    }
    }

    Let me know if you need any further details.

    Thanks,
    Siva

  14. Hi Siva,

    A kind request can u give an example tutorial for same spring hibernate MVC using GWT hope it will be helpful to many like me.

    Thanks,

    Joshua.

  15. man i am a newbie and i dlded ur code , import it as a project in eclipse, n tried to run it with tomcat 6 but i keep getting "PageNotFound – No mapping found for HTTP request with URI [/SpringMVCHibernate/viewAllContacts.do] in DispatcherServlet with name 'dispatcher'
    " …. any idea wat i m doing wrong ???

  16. Hi,
    I just downloaded the zip and imported into eclipse and ran it. It is working fine.

    When I check in your logs i found the following difference.

    After the log statement,

    SessionFactoryObjectFactory – Not binding factory to JNDI, no JNDI name configured

    I am getting the following URL Mapping log statements.

    DefaultAnnotationHandlerMapping – Mapped URL path [/searchContacts] onto handler 'contactsControllers'
    DefaultAnnotationHandlerMapping – Mapped URL path [/searchContacts.*] onto handler 'contactsControllers'
    DefaultAnnotationHandlerMapping – Mapped URL path [/searchContacts/] onto handler 'contactsControllers'
    DefaultAnnotationHandlerMapping – Mapped URL path [/viewAllContacts] onto handler 'contactsControllers'
    DefaultAnnotationHandlerMapping – Mapped URL path [/viewAllContacts.*] onto handler 'contactsControllers'
    DefaultAnnotationHandlerMapping – Mapped URL path [/viewAllContacts/] onto handler 'contactsControllers'
    DefaultAnnotationHandlerMapping – Mapped URL path [/saveContact] onto handler 'contactsControllers'
    DefaultAnnotationHandlerMapping – Mapped URL path [/saveContact.*] onto handler 'contactsControllers'
    DefaultAnnotationHandlerMapping – Mapped URL path [/saveContact/] onto handler 'contactsControllers'
    DefaultAnnotationHandlerMapping – Mapped URL path [/updateContact] onto handler 'contactsControllers'
    DefaultAnnotationHandlerMapping – Mapped URL path [/updateContact.*] onto handler 'contactsControllers'
    DefaultAnnotationHandlerMapping – Mapped URL path [/updateContact/] onto handler 'contactsControllers'
    DefaultAnnotationHandlerMapping – Mapped URL path [/deleteContact] onto handler 'contactsControllers'
    DefaultAnnotationHandlerMapping – Mapped URL path [/deleteContact.*] onto handler 'contactsControllers'
    DefaultAnnotationHandlerMapping – Mapped URL path [/deleteContact/] onto handler 'contactsControllers'
    DefaultAnnotationHandlerMapping – Mapped URL path [/home] onto handler 'contactsControllers'
    DefaultAnnotationHandlerMapping – Mapped URL path [/home.*] onto handler 'contactsControllers'
    DefaultAnnotationHandlerMapping – Mapped URL path [/home/] onto handler 'contactsControllers'
    HibernateTransactionManager – Using DataSource [org.springframework.jdbc.datasource.DriverManagerDataSource@15738e0] of Hibernate SessionFactory for HibernateTransactionManager
    ContextLoader – Root WebApplicationContext: initialization completed in 3297 ms.
    ….
    ….

    But in your logs i didn't see those URL Mapping log statements.

    Please check whether you changed any package names or file locations.

    In resources/applicationContext.xml I have given the base package name as follows:

    <context:component-scan base-package="com.sivalabs" />

    So if you have changed the package name Spring won't identify the Controllers annotated with @Controller. Please check and let me know.

    Thanks,
    Siva

  17. Hi,
    In dispatcher-servlet.xml, you have changed the prefix value to WEB-INF/jsp/.
    But you have not moved the jsp folder into WEB-INF. Check that once.

    Thanks,
    Siva

  18. ohh i forgot to revert tht back , actually i was trying to change it see if anything changes in the output. it doesnt, i get the same result with both.

    regards,
    khizar

  19. But after changing the prefix value its working fine for me.

    As the last thing i would suggest you to cleanup the project and try once. Or create a new Dynamic web project and copy the src, resources, WebContent folder and run.

    Thanks,
    Siva

  20. ok .. thanx alot man .. i also think mnow tht the problem is with my environment maybe … i'll try it and post if i find a problem. Thanx for the help

    regards,
    khizar

  21. Really nice article on spring web mvc 3.0. I need some guidance on converting this application from Spring-Hibernate to Spring-Jdbc. I am not sure how to hook the jdbcTemplate in ContactsDao in spring config files. Your guidance is appreciated.

  22. Hello,

    I tested the sample app. I got following error messages when app starts up;
    java.lang.NoSuchMethodError: javax.servlet.ServletContext.getContextPath()Ljava/lang/String;
    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:431)
    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:459)
    at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:340)
    at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:307)…….

  23. Hi Siva,

    Thanks for a great tutorial,if poss can you create a crud in gwt using spring hibernate,it will be very helpful for newbees like us,please.

    Thanks,

    Joshua Daniel.

  24. Hi siva,

    Good tutorial, keep posting,
    one thing I need to ask,How do you format the code in blog, as I can not see that option in same my blogspot. And how do you attache a file ( I could not find these two options)

  25. Hi siva,
    When I ran this code, I'm getting following error:

    SEVERE: Servlet.service() for servlet [appServlet] in context with path [/phonebook] threw exception [Request processing failed; nested exception is org.hibernate.HibernateException: No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here] with root cause
    org.hibernate.HibernateException: No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here
    at org.springframework.orm.hibernate3.SpringSessionContext.currentSession(SpringSessionContext.java:63)
    at org.hibernate.impl.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:622)
    at com.deep.contacts.ContactsDAO.getAllContacts(ContactsDAO.java:39)
    at com.deep.contacts.ContactsController.getAllContacts(ContactsController.java:62)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)

    Any help would be appreciated.
    regards,
    DP

  26. I missed tx:annotation-driven in context file. Apparently, you have to put this tag in both application-context and dispatcher-servlet.xml files.
    DP

  27. Hi Siva, nice article. I imported your code in eclipse and tried to run it. I got the following message
    "PageNotFound – No mapping found for HTTP request with URI [/SpringMVCHibernate/viewAllContacts.do] in DispatcherServlet with name 'dispatcher'" in the console.

    I tried to run it through the eclipse. i.e run as 'Run on server'.

    Also, the index.jsp file is showing an error as "The method sendRedirect(String) from the type HttpServletResponse refers to the missing type String" for the response.sendRedirect attribute.

    Any suggestions.

  28. Hi Shiva, I liked your example pretty much.. don't care for discouraging people.
    I am trying some more beautiful things with your approach and let u know if discovered anything new..or addon ๐Ÿ™‚

  29. Hey its awesome example posted here……

    there is some minor changes but it is best for easily learning Spring crud flow……

    Good going buddy………

    once again thanks a lot friend………..

  30. Hi siva,
    When I ran this code, I'm getting the error as
    Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener
    org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'contactsController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.database.ContactsDAO com.lf.controller.ContactsController.contactsDAO; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.database.ContactsDAO] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

  31. Hi Siva,

    good post. I'm trying to learn the basics of Spring and I have one fundamental question. If I need to maintain 50-60 tables in my application, what is the best approach? One controller for each entity? Or mixing many entities with one controller? (I suppose that each entity has its own set of views). Are @Service needed at all in a CRUD application. I'm sorry but I'm little confused from all the tutorials I have read regarding Spring.
    And if you excuse me one more question. Is it a better practice to split project into subprojects (for example domain, persistence, web etc)?

    Thank you for your time

  32. Hi,
    If your application involve more number of tables with only CRUD operations have a look at OpenXava which simplifies the CRUD operations very much.
    I prefer having one controller per Entity because we can write reusable template kind of Controller with generics so that we can avoid repeated coding.
    SpringMVC simplifies web development a lot but try having a look at Grails which built on top of Spring which is even more easier to develop CRUD apps. For simple CRUD apps, separating web, service, persistence code is not required(my opinion).

  33. Thank you Siva for your help.
    Actually is a lot more that CRUD, therefore I'll stick with Spring MVC and I'll try to split layers.

    But, again I'm a little bit confused with @Service. In general, when do you use this? For my app, it seems like an extra unecessary layer between controller and dao.

    Thank you again.

  34. Hi siva,
    I got the below error, when i tried to run the code

    SEVERE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener
    org.springframework.beans.factory.BeanDefinitionStoreException: Parser configuration exception parsing XML from ServletContext resource [/WEB-INF/resources/applicationContext.xml]; nested exception is javax.xml.parsers.ParserConfigurationException: Unable to validate using XSD: Your JAXP provider [gnu.xml.dom.JAXPFactory@12c8fa8] does not support XML Schema. Are you running on Java 1.4 with Apache Crimson? Upgrade to Apache Xerces (or Java 1.5) for full XSD support.
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:404)
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:334)

    Pls help me in resolving the issue.

    Thanks,
    Lalika

  35. Hi Siva,

    I could resolve the above mentioned error by placing these two jars xerces,xercesImpl in WEB-INF/lib path.

    Thanks,
    Lalika

  36. any one explain me plz
    if multible users are concurrently accessing the singleton single bean then any performance issue is arraised.if arraised can any body explain plz.. how wecan resolve it.

  37. Hi Silva !!!

    Thank you for this article. It's very clear !

    I completed CRUD example . But I want "PAGING IN YOUR CRUD EXAMPLE" ???

    How to Paging in your CRUD ???

    Please contact me : skype: kienng_tms . Email : kienng2012@gmail.com.

    Thank you Silva ! Best wishes for you !

  38. Hi Siva,

    i'm getting this error, please give me solution

    org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'managerController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.iton.eoffice.service.ManagerService com.iton.eoffice.controller.ManagerController.managerService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'managerServiceImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.iton.eoffice.dao.ManagerDAO com.iton.eoffice.service.ManagerServiceImpl.managerDAO; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'managerDAOImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.hibernate.SessionFactory com.iton.eoffice.dao.ManagerDAOImpl.sessionFactory; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in ServletContext resource [/WEB-INF/spring-servlet.xml]: Invocation of init method failed; nested exception is java.lang.NullPointerException

    Any help would be appreciated.
    regards,
    Ganesh

  39. Hi Siva,

    on my research:
    -If this web framework example has business logic coded in whatever the Controller is, then it is not accurate.
    -the Model represents business logic and business data.
    -"Model" can be comprised of various entities including ORM objects and DAOs
    -The Model also includes other objects besides data objects. The other Model objects are business objects which contain business logic.

    But what I can see in your example:
    – Model have no business logic, have only business data
    – Model not include ORM or DAO, model should work with data source, we no need to create external ORM or DAO.

    So, Model = Rule + Data + DAO
    Please correct me, if I am wrong.

    Regards.

  40. Hi Spider Man :-),
    You are 100% correct on your points.

    And my example is to show how to glue things together with SpringMVC, JPA etc and very very simple CRUD application and so doesn't have business logic.

    But in real project definitely there will be business logic.

    -Siva

  41. Hi I tried your code but I encountered some problem see errors below:

    JDBCExceptionReporter – SQL Error: 1045, SQLState: 28000
    JDBCExceptionReporter – Access denied for user 'root'@'localhost' (using password: YES)
    JDBCExceptionReporter – SQL Error: 1045, SQLState: 28000
    JDBCExceptionReporter – Access denied for user 'root'@'localhost' (using password: YES)

    I have already set the username and password in config.properties still got the same errors.

    Pls. advise thanks a lot.

  42. Hi siva,
    I got the below error, when i tried to run the code

    Hibernate: insert into CONTACTS (address, dob, email, gender, mobile, name, phone) values (?, ?, ?, ?, ?, ?, ?)
    4 Dec, 2012 8:54:50 AM org.apache.catalina.core.StandardWrapperValve invoke
    SEVERE: Servlet.service() for servlet dispatcher threw exception
    org.hibernate.MappingException: Dialect does not support identity key generation
    at org.hibernate.dialect.Dialect.getIdentitySelectString(Dialect.java:549)
    at org.hibernate.dialect.Dialect.getIdentitySelectString(Dialect.java:538)

  43. Im using SEQUENCE, but it's not working, im getting following error

    SEVERE: Servlet.service() for servlet dispatcher threw exception
    java.sql.SQLException: ORA-02289: sequence does not exist

    at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:112)

  44. You need to create the sequence first and then use it for id generation.

    SQL>CREATE SEQUENCE SCHEMA.ID_SEQ;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO, generator = "idGenerator")
    @SequenceGenerator(name="idGenerator", sequenceName="ID_SEQ")

  45. Im using this query to solved my problem

    i got little bit confident because i learn more from this example

    thank a lot siva sir

    CREATE SEQUENCE id_seq START WITH 1 INCREMENT BY 1 NOCYCLE;

    adding that sequence fixed the problem

  46. My Contact.java code is here

    public class Contact{
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "idGenerator")
    @SequenceGenerator(sequenceName="id", name = "idGenerator")
    private int id;……}
    but same error

  47. When am running your example on tomcat 6 and jre 1.6 am getting the following error. i have created new dynamic web project and replaced src,resource,webContent .here am giving you server log of error
    SEVERE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener
    java.lang.IllegalStateException: Failed to invoke Servlet 2.5 getContextPath method
    at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:268)
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:197)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:47)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:3934)
    at org.apache.catalina.core.StandardContext.start(StandardContext.java:4429)
    at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045)
    at org.apache.catalina.core.StandardHost.start(StandardHost.java:722)
    at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045)
    at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:443)
    at org.apache.catalina.core.StandardService.start(StandardService.java:516)
    at org.apache.catalina.core.StandardServer.start(StandardServer.java:710)
    at org.apache.catalina.startup.Catalina.start(Catalina.java:583)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:288)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:413)
    Caused by: java.lang.NoSuchMethodException: javax.servlet.ServletContext.getContextPath()
    at java.lang.Class.getMethod(Class.java:1605)
    at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:263)
    … 17 more
    plz help me to resolve this issue>>>>

  48. Hi Siva
    Congrats for the Spring Hibernate CRUD example ,
    I had to put additional jar Java.util as well to make ut work , plus it is giving some html tags as obsolete for HTML5 , may be becausae , i am using Java7.r17, i used DB2 UDB LUW as database
    Also , i look forward to MAVEN POM , I am not able to figure out MAVEN dependencies & Repositories to use for all these jars for the latest release, versions of Spring , Hibernate & other java objects libraries Etc

  49. Hi Siva, Trying to run your example using GlassFishSrver3.1.2 and netbeans 7.3 IDE receiving the fallowing

    WARNING: No mapping found for HTTP request with URI [/SpringHibernate/viewAllCotacts.do] in DispatcherServlet with name 'dispatcher'

    Please suggest.

  50. Hi Siva,
    can you tell me how can it will close the session.
    suppose we have done create operation. than we are not closing the session.

    So is it Possible to do it with normal hiber-net approach.
    where we are having Common singletone hibernet session object..& related configuration.

    and how can i do the same without using annotation for hibernet.. ?
    Please guide me for making this without annotation.

  51. Hi siva,
    Really amazing tutorial.. If u donot mind May I suggest u to put the Screen shots of the project structure and the output screens then It will be more Attractive and beginners can easily understand more efficiently…

  52. Hi Siva,

    I was trying this example, it ran well. Now I want to add new page, but it throwing me following error.

    "Neither BindingResult nor plain target object for bean name 'newAddress' available as request attribute"

    Controller code:
    ———————–
    @RequestMapping(value="/saveAddress", method=RequestMethod.GET)
    public ModelAndView newaddressForm()
    {
    ModelAndView mav = new ModelAndView("newAddress");
    Address address = new Address();
    mav.getModelMap().put("newAddress", address);
    return mav;
    }

    @RequestMapping(value="/saveAddress", method=RequestMethod.POST)
    public String create(@ModelAttribute("newAddress")Address address, BindingResult result, SessionStatus status)
    {
    validator.validate(address, result);
    if (result.hasErrors())
    {
    return "newAddress";
    }
    addressDAO.save(address);
    status.setComplete();
    return "redirect:viewAllAddress.do";
    }

    JSP Code:
    —————

  53. Hi siva,

    I am facing below error kindly help

    Oct 23, 2013 5:00:36 PM org.apache.catalina.core.StandardContext listenerStart
    SEVERE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener
    org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path resource [applicationContext.xml]; nested exception is java.io.FileNotFoundException: class path resource [applicationContext.xml] cannot be opened because it does not exist
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:341)
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:302)
    at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:143)
    at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:178)
    at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:149)
    at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:124)
    at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:93)
    at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:130)
    at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:467)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:397)
    at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:276)
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:197)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:47)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4701)
    at org.apache.catalina.core.StandardContext$1.call(StandardContext.java:5204)
    at org.apache.catalina.core.StandardContext$1.call(StandardContext.java:5199)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334)
    at java.util.concurrent.FutureTask.run(FutureTask.java:166)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
    at java.lang.Thread.run(Thread.java:722)
    Caused by: java.io.FileNotFoundException: class path resource [applicationContext.xml] cannot be opened because it does not exist
    at org.springframework.core.io.ClassPathResource.getInputStream(ClassPathResource.java:158)
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:328)
    … 20 more

    Thanks,
    Wasif

  54. Hai,
    When i run the project i got below error i am using sql server 2008

    JDBCExceptionReporter – SQL Error: 0, SQLState: 08S01
    JDBCExceptionReporter – The TCP/IP connection to the host ERPSERVERSQL, port 1433 has
    failed. Error: "null. Verify the connection properties. Make sure that an instance of SQL
    Server is running on the host and accepting TCP/IP connections at the port. Make sure
    that TCP connections to the port are not blocked by a firewall.".

  55. Hai,
    If i run the project i got below error can you help me please

    JDBCExceptionReporter – SQL Error: 0, SQLState: 08S01
    JDBCExceptionReporter – The TCP/IP connection to the host ERPSERVERSQL, port 1433 has
    failed. Error: "null. Verify the connection properties. Make sure that an instance of SQL
    Server is running on the host and accepting TCP/IP connections at the port. Make sure
    that TCP connections to the port are not blocked by a firewall.".

  56. I'm with you… nice tutorial but waaaaay too much boilerplate code! Thereโ€™s a great RAD tool out called Jigy Generator that automatically spits you out a fully configured spring project which can already connect to your database, authenticate users, handle file uploads, etc. It even creates daoโ€™s, domain objects and validators in your project by reverse engineering your database. This way you don't have to get mired in the low level details of spring and hibernate… It Just Works! You can download the project at http://www.getjigy.com

  57. SEVERE: Servlet.service() for servlet [dispatcher] in context with path [/SpringMVCHibernate] threw exception [Request processing failed; nested exception is org.springframework.transaction.CannotCreateTransactionException: Could not open Hibernate Session for transaction; nested exception is org.hibernate.exception.GenericJDBCException: Cannot open connection] with root cause
    java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: YES)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1073)

Leave a Reply

Your email address will not be published. Required fields are marked *