Java and J2EE Tutorials, Jsp and Servlet Tutorials, Spring MVC, Solr, XML, JSON Examples, Hibernate & Struts 2 Hello World projects



Sunday, 25 May 2014

Spring MVC and Hibernate Integration CRUD with Maven (Spring 4 + Hibernate 4 + Maven 3)

In this particular project we will see how to integrate Spring MVC 4 with Hibernate4 project with Maven and will perform crud operations using MySql Database. We will see what dependencies are required to setup Spring4 with Hibernate4 and how to configure SessionFactory and Spring configurations.


Objectives

1) How to integrate Spring 4 MVC with HIbernate 4 using Maven
2) What dependencies are required to integrate Hibernate 4 with Spring 4
3) How to setup SessionFactory with Hibernate 4
4) How to perform Create, Add, Edit and Delete operations on a Spring project with Hibernate.


How to integrate Spring 4 MVC with HIbernate 4 using Maven

Let us start our discussion with getting a simple web project from maven, if you are new to maven go to How to setup a web project with maven.
Assuming that we have a simple web project with maven with us and imported that in Eclipse IDE, now let us discuss how to setup the project, follow the steps mentioned in the rest part of the blow one by one:


Database setup

Let us first create a dummy database for our project, below is a mysql script please copy and execute it in your query editor.
-- Dumping database structure for springhibernate_db
CREATE DATABASE IF NOT EXISTS `springhibernate_db` /*!40100 DEFAULT CHARACTER SET latin1 */;
USE `springhibernate_db`;


-- Dumping structure for table springhibernate_db.employee
CREATE TABLE IF NOT EXISTS `employee` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `first_name` varchar(45) DEFAULT NULL,
  `last_name` varchar(45) DEFAULT NULL,
  `email` varchar(45) DEFAULT NULL,
  `phone` varchar(45) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=latin1;

-- Dumping data for table springhibernate_db.employee: ~3 rows (approximately)
/*!40000 ALTER TABLE `employee` DISABLE KEYS */;
INSERT INTO `employee` (`id`, `first_name`, `last_name`, `email`, `phone`) VALUES
 (10, 'Virat', 'Kohli', 'virat@beingjavaguys.com', '89876787890'),
 (11, 'Sachin', 'Tendulkar', 'sachin@india.com', '89898989898'),
 (12, 'Virendra', 'Sehwag', 'viru@delhi.com', '8976778789');


Maven dependencies required to setup Spring MVC 4 with Hibernate 4 : pom.xml

We are done with getting a simple Web project with maven and database setup let us add required dependencies to it.
<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>com.beingjavaguys.sphbn</groupId>
 <artifactId>SpringHibernateAnnotations</artifactId>
 <packaging>war</packaging>
 <version>1.0-SNAPSHOT</version>
 <name>SpringHibernateAnnotations Maven Webapp</name>
 <url>http://maven.apache.org</url>

 <properties>
  <spring.version>4.0.5.RELEASE</spring.version>
  <hibernate.version>4.3.5.Final</hibernate.version>
  <log4j.version>1.2.17</log4j.version>
  <jdk.version>1.7</jdk.version>
  <context.path>SpringHibernateAnnotations</context.path>
 </properties>
 <developers>

  <developer>
   <id>Nagesh Chauhan</id>
   <email>beingjavaguy@gmail.com</email>
   <organization>beingjavaguys.com</organization>
   <organizationUrl>http://www.beingjavaguys.com</organizationUrl>
   <roles>
    <role>Java Developer</role>
   </roles>
   <timezone>+5:30</timezone>
  </developer>
 </developers>

 <build>
  <finalName>${pom.artifactId}</finalName>

  <plugins>
   <!-- Maven compiler plugin -->
   <plugin>
    <artifactId>maven-compiler-plugin</artifactId>
    <configuration>
     <source>${jdk.version}</source>
     <target>${jdk.version}</target>
    </configuration>
   </plugin>
  </plugins>
 </build>
 <dependencies>
  <dependency>
   <groupId>log4j</groupId>
   <artifactId>log4j</artifactId>
   <version>${log4j.version}</version>
  </dependency>

  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-orm</artifactId>
   <version>${spring.version}</version>
  </dependency>
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-jdbc</artifactId>
   <version>${spring.version}</version>
  </dependency>

  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-web</artifactId>
   <version>${spring.version}</version>
  </dependency>

  <dependency>
   <groupId>org.hibernate</groupId>
   <artifactId>hibernate-entitymanager</artifactId>
   <version>${hibernate.version}</version>
  </dependency>

  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-webmvc</artifactId>
   <version>${spring.version}</version>
  </dependency>

  <dependency>
   <groupId>jstl</groupId>
   <artifactId>jstl</artifactId>
   <version>1.2</version>
  </dependency>
  <dependency>
   <groupId>mysql</groupId>
   <artifactId>mysql-connector-java</artifactId>
   <version>5.1.6</version>
  </dependency>


 </dependencies>
</project>


Now clean and install the project from maven console 'mvn clean install' and supply 'maven eclipse:eclipse -Dwtpversion=2.0' again and refresh the project in eclipse so that all required dependencies are downloaded and imported in eclipse 'Deployment Assemblies'.


\src\main\webapp\WEB-INF\web.xml

Let us now add 'DispatcherServlet' to our web.xml file to tell the container that all upcoming requests will be handled by Spring itself.
<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_2_5.xsd"
 version="2.5">

 <display-name>Sample Spring Maven Project</display-name>

 <servlet>
  <servlet-name>mvc-dispatcher</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  <init-param>
   <param-name>contextConfigLocation</param-name>
   <param-value>/WEB-INF/spring-config.xml</param-value>
  </init-param>
  <load-on-startup>1</load-on-startup>
 </servlet>

 <servlet-mapping>
  <servlet-name>mvc-dispatcher</servlet-name>
  <url-pattern>/</url-pattern>
 </servlet-mapping>

</web-app>


\src\main\webapp\WEB-INF\spring-config.xml

This is simple spring configuration file, we have added a datasource bean here which is getting values from a property file, secondly hibernate session factory is being configured and a view resolver is being added to render related jsp's.
<?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:util="http://www.springframework.org/schema/util" xmlns:mvc="http://www.springframework.org/schema/mvc"
 xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
  http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
  http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd
  http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">

 <context:component-scan base-package="com.beingjavaguys.controller" />
 <context:property-placeholder location="classpath:database.properties" />
 <mvc:annotation-driven />

 <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.hibernate4.LocalSessionFactoryBean">
  <property name="dataSource" ref="dataSource" />
  <property name="annotatedClasses">  
            <list>  
                <value>com.beingjavaguys.domain.Employee</value>  
            </list>  
        </property> 
  <property name="hibernateProperties">
   <props>
    <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
    <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
   </props>
  </property>
 </bean>

 <bean id="txManager"
  class="org.springframework.orm.hibernate4.HibernateTransactionManager">
  <property name="sessionFactory" ref="sessionFactory" />
 </bean>

 <bean id="persistenceExceptionTranslationPostProcessor"
  class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />
  
 <bean
  class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  <property name="prefix">
   <value>/WEB-INF/pages/</value>
  </property>
  <property name="suffix">
   <value>.jsp</value>
  </property>
 </bean>


 <bean id="dataDaoImpl" class="com.beingjavaguys.dao.DataDaoImpl" />
 <bean id="dataServiceImpl" class="com.beingjavaguys.services.DataServiceImpl" />

</beans>


\src\main\java\com\beingjavaguys\controller\DataController.java

Now let us add a controller to the project, we have added all required request-mappings to it to perform CRUD operations. The code is self explanatory.
package com.beingjavaguys.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
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.beingjavaguys.domain.Employee;
import com.beingjavaguys.services.DataService;

@Controller
public class DataController {

 @Autowired
 DataService dataService;

 @RequestMapping("form")
 public ModelAndView getForm(@ModelAttribute Employee employee) {
  return new ModelAndView("form");
 }

 @RequestMapping("register")
 public ModelAndView registerUser(@ModelAttribute Employee employee) {
  dataService.insertRow(employee);
  return new ModelAndView("redirect:list");
 }

 @RequestMapping("list")
 public ModelAndView getList() {
  List employeeList = dataService.getList();
  return new ModelAndView("list", "employeeList", employeeList);
 }

 @RequestMapping("delete")
 public ModelAndView deleteUser(@RequestParam int id) {
  dataService.deleteRow(id);
  return new ModelAndView("redirect:list");
 }

 @RequestMapping("edit")
 public ModelAndView editUser(@RequestParam int id,
   @ModelAttribute Employee employee) {
  Employee employeeObject = dataService.getRowById(id);
  return new ModelAndView("edit", "employeeObject", employeeObject);
 }

 @RequestMapping("update")
 public ModelAndView updateUser(@ModelAttribute Employee employee) {
  dataService.updateRow(employee);
  return new ModelAndView("redirect:list");
 }

}



\src\main\java\com\beingjavaguys\domain\Employee.java

Now we will add an 'Entity' class to the project, this class represents the table in database. We have added '@Entity' annotation to make hibernate recognize that this POJO is a entity in db. Variable names are automatically mapped to table columns id they are same. In case of any difference we have to annotate the fields with '@Column' annotations. @Id represents surrogate key for table.
package com.beingjavaguys.domain;

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

@Entity
public class Employee {

 @Id
 @GeneratedValue
 private int id;

 @Column(name = "first_name")
 private String firstName;

 @Column(name = "last_name")
 private String lastName;

 private String email;
 private String phone;

 public int getId() {
  return id;
 }

 public void setId(int id) {
  this.id = id;
 }

 public String getFirstName() {
  return firstName;
 }

 public void setFirstName(String firstName) {
  this.firstName = firstName;
 }

 public String getLastName() {
  return lastName;
 }

 public void setLastName(String lastName) {
  this.lastName = lastName;
 }

 public String getEmail() {
  return email;
 }

 public void setEmail(String email) {
  this.email = email;
 }

 public String getPhone() {
  return phone;
 }

 public void setPhone(String phone) {
  this.phone = phone;
 }

}




\src\main\java\com\beingjavaguys\dao\DataDao.java


package com.beingjavaguys.dao;

import java.util.List;

import com.beingjavaguys.domain.Employee;

public interface DataDao {
 public int insertRow(Employee employee);

 public List getList();

 public Employee getRowById(int id);

 public int updateRow(Employee employee);

 public int deleteRow(int id);

}




\src\main\java\com\beingjavaguys\dao\DataDaoImpl.java

All Hibernate related action goes here, operations related to 'Create, Insert, Update and Delete' are being performed in appropriate methods, we are getting session object from an autowired sessionfactory.


package com.beingjavaguys.dao;

import java.io.Serializable;
import java.util.List;

import javax.transaction.Transactional;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;

import com.beingjavaguys.domain.Employee;

public class DataDaoImpl implements DataDao {

 @Autowired
 SessionFactory sessionFactory;

 @Override
 @Transactional
 public int insertRow(Employee employee) {
  Session session = sessionFactory.openSession();
  Transaction tx = session.beginTransaction();
  session.saveOrUpdate(employee);
  tx.commit();
  Serializable id = session.getIdentifier(employee);
  session.close();
  return (Integer) id;
 }

 @Override
 public List getList() {
  Session session = sessionFactory.openSession();
  @SuppressWarnings("unchecked")
  List employeeList = session.createQuery("from Employee")
    .list();
  session.close();
  return employeeList;
 }

 @Override
 public Employee getRowById(int id) {
  Session session = sessionFactory.openSession();
  Employee employee = (Employee) session.load(Employee.class, id);
  return employee;
 }

 @Override
 public int updateRow(Employee employee) {
  Session session = sessionFactory.openSession();
  Transaction tx = session.beginTransaction();
  session.saveOrUpdate(employee);
  tx.commit();
  Serializable id = session.getIdentifier(employee);
  session.close();
  return (Integer) id;
 }

 @Override
 public int deleteRow(int id) {
  Session session = sessionFactory.openSession();
  Transaction tx = session.beginTransaction();
  Employee employee = (Employee) session.load(Employee.class, id);
  session.delete(employee);
  tx.commit();
  Serializable ids = session.getIdentifier(employee);
  session.close();
  return (Integer) ids;
 }

}



\src\main\java\com\beingjavaguys\services\DataService.java


package com.beingjavaguys.services;

import java.util.List;

import com.beingjavaguys.domain.Employee;

public interface DataService {
 public int insertRow(Employee employee);

 public List getList();

 public Employee getRowById(int id);

 public int updateRow(Employee employee);

 public int deleteRow(int id);

}




\src\main\java\com\beingjavaguys\services\DataServiceImpl.java

A service layer does nothing but it makes the code more flexible and reusable, using an Service layer in your projects makes it easy to test the data layer.
package com.beingjavaguys.services;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import com.beingjavaguys.dao.DataDao;
import com.beingjavaguys.domain.Employee;

public class DataServiceImpl implements DataService {
 
 @Autowired
 DataDao dataDao;

 @Override
 public int insertRow(Employee employee) {
  return dataDao.insertRow(employee);
 }

 @Override
 public List getList() {
  return dataDao.getList();
 }

 @Override
 public Employee getRowById(int id) {
  return dataDao.getRowById(id);
 }

 @Override
 public int updateRow(Employee employee) {
  return dataDao.updateRow(employee);
 }

 @Override
 public int deleteRow(int id) {
  return dataDao.deleteRow(id);
 }

}





\src\main\webapp\WEB-INF\pages\form.jsp

Here we have very first jsp file, this will render a user registration form. The data entered here will be persisted to the database table using Hibernate.


<%@ page language="java" contentType="text/html; charset=UTF-8"
 pageEncoding="UTF-8"%>
<%@ 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=UTF-8">
<title>Being Java Guys | Registration Form</title>
</head>
<body>
 <center>

  <div style="color: teal; font-size: 30px">Being Java Guys |
   Registration Form</div>



  <c:url var="userRegistration" value="saveUser.html" />
  <form:form id="registerForm" modelAttribute="employee" method="post"
   action="register">
   <table width="400px" height="150px">
    <tr>
     <td><form:label path="firstName">First Name</form:label>
     </td>
     <td><form:input path="firstName" />
     </td>
    </tr>
    <tr>
     <td><form:label path="lastName">Last Name</form:label>
     </td>
     <td><form:input path="lastName" />
     </td>
    </tr>
    <tr>
     <td><form:label path="email">Email</form:label>
     </td>
     <td><form:input path="email" />
     </td>
    </tr>
    <tr>
     <td><form:label path="phone">Phone</form:label>
     </td>
     <td><form:input path="phone" />
     </td>
    </tr>
    <tr>
     <td></td>
     <td><input type="submit" value="Register" /></td>
    </tr>
   </table>
  </form:form>


  <a href="list">Click Here to see User List</a>
 </center>
</body>
</html>



\src\main\webapp\WEB-INF\pages\list.jsp

This view will show up a list of all employees stored in Database, we have associated 'Edit' and 'Delete' functionality to them so that records can be edited and deleted on the fly.
<%@ page language="java" contentType="text/html; charset=UTF-8"
 pageEncoding="UTF-8"%>
<%@ 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=UTF-8">
<title>Being Java Guys | User Details</title>
</head>
<body>
 <center>

  <div style="color: teal; font-size: 30px">Being Java Guys | User
   Details</div>

  <c:if test="${!empty employeeList}">
   <table border="1" bgcolor="black" width="600px">
    <tr
     style="background-color: teal; color: white; text-align: center;"
     height="40px">
     
     <td>First Name</td>
     <td>Last Name</td>
     <td>Email</td>
     <td>Phone</td>
     <td>Edit</td>
     <td>Delete</td>
    </tr>
    <c:forEach items="${employeeList}" var="user">
     <tr
      style="background-color: white; color: black; text-align: center;"
      height="30px">
      
      <td><c:out value="${user.firstName}" />
      </td>
      <td><c:out value="${user.lastName}" />
      </td>
      <td><c:out value="${user.email}" />
      </td>
      <td><c:out value="${user.phone}" />
      </td>
      <td><a href="edit?id=${user.id}">Edit</a></td>
      <td><a href="delete?id=${user.id}">Delete</a></td>
     </tr>
    </c:forEach>
   </table>
  </c:if>


  <a href="form">Click Here to add new User</a>
 </center>
</body>
</html>





\src\main\webapp\WEB-INF\pages\form.jsp

This view will render a edit form with auto fill values of employee table, once submitted all required updates will be reflected to db.

<%@ page language="java" contentType="text/html; charset=UTF-8"
 pageEncoding="UTF-8"%>
<%@ 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=UTF-8">
<title>Being Java Guys | Edit User Details</title>
</head>
<body>
 <center>

  <div style="color: teal; font-size: 30px">Being Java Guys |
   Edit Details</div>



  <c:url var="userRegistration" value="saveUser.html" />
  <form:form id="registerForm" modelAttribute="employee" method="post"
   action="update">
   <table width="400px" height="150px">
    <tr>
     <td><form:label path="firstName">First Name</form:label></td>
     <td><form:input path="firstName" value="${employeeObject.firstName}" /></td>
    </tr>
    <tr>
     <td><form:label path="lastName">Last Name</form:label></td>
     <td><form:input path="lastName" value="${employeeObject.lastName}"/></td>
    </tr>
    <tr>
     <td><form:label path="email">Email</form:label></td>
     <td><form:input path="email" value="${employeeObject.email}"/></td>
    </tr>
    <tr>
     <td><form:label path="phone">Phone</form:label></td>
     <td><form:input path="phone" value="${employeeObject.phone}"/></td>
    </tr>
    <tr>
     <td></td>
     <td><input type="submit" value="Update" />
     </td>
    </tr>
   </table>
  </form:form>


  
 </center>
</body>
</html>




\src\main\webapp\index.jsp

At the end, we have redirected the default flow from 'index.jsp' to our registration form so that 'form' will open on the start up of project.
<%response.sendRedirect("form");%>
<html>
<body>
<h2>Hello World!</h2>
</body>
</html>




Now we are all done, now if everything goes right and you have configured things correctly, we will see following screens on the browser.





That’s all about "Spring MVC and Hibernate Integration CRUD with Maven" In upcoming blogs we will see more about Spring, Hibernate, Java and Other opensource technologies.








Thanks for reading !
Being Java Guys Team

Download "Spring4 + Hibernate4 + Maven3 Integration Example Project" from "SkyDrive"





35 comments:

  1. HTTP Status 500 - Servlet.init() for servlet mvc-dispatcher threw exception

    type Exception report

    message Servlet.init() for servlet mvc-dispatcher threw exception

    description The server encountered an internal error that prevented it from fulfilling this request.

    exception

    javax.servlet.ServletException: Servlet.init() for servlet mvc-dispatcher threw exception
    org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
    org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
    org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
    org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
    org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
    org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
    org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
    java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    java.lang.Thread.run(Thread.java:745)

    root cause

    org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping#0': Invocation of init method failed; nested exception is org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [com.beingjavaguys.dao.DataDaoImpl] for bean with name 'dataDaoImpl' defined in ServletContext resource [/WEB-INF/spring-config.xml]; nested exception is java.lang.ClassNotFoundException: com.beingjavaguys.dao.DataDaoImpl
    Related cause: org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [com.beingjavaguys.dao.DataDaoImpl] for bean with name 'dataDaoImpl' defined in ServletContext resource [/WEB-INF/spring-config.xml]; nested exception is java.lang.ClassNotFoundException: com.beingjavaguys.dao.DataDaoImpl
    Related cause: org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [com.beingjavaguys.services.DataServiceImpl] for bean with name 'dataServiceImpl' defined in ServletContext resource [/WEB-INF/spring-config.xml]; nested exception is java.lang.ClassNotFoundException: com.beingjavaguys.services.DataServiceImpl
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1553)

    ReplyDelete
    Replies
    1. it says it cannot locate the classes.. from what it looks like is that your beans and classes are not matched correctly.. you have dataDaoImpl and DataDaoImpl and the same thing is with yout services class.. make sure you configure it properly..

      Delete
  2. and persistence.xml?

    ReplyDelete
  3. This Apllication Works just too fine , only one issue is going when i try to edit row details a new entry is added? Can you suggest whats the issue?

    ReplyDelete
    Replies
    1. I've got an issue like yours.
      at updateRow method from DataDaoImpl
      if i change saveOrUpdate to update, it'll show a error :

      Request processing failed; nested exception is org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1

      Delete
    2. I can imagine that is because there is no check if the employee record was modified... then it just add and doesn't update

      Delete
  4. my registration doesn't work, apart from that, i think its fine..

    ReplyDelete
  5. The file database.properties is missing

    ReplyDelete
  6. very clear and fine works 100% for me on STS

    ReplyDelete
    Replies
    1. Can you update a record? mine is just creating a new record

      Delete
  7. who has solved the editing issue?

    ReplyDelete
  8. Just try this code in the edit form :


    First Name
    ......

    In fact, we need to give the "id" of employee that we update, even if we don't show it.

    ReplyDelete
  9. Sorry this code :

    ...........
    form:hidden path="id" value="${teamsEntityObject.id}"
    .........

    ReplyDelete
  10. replace also "teamEntityObject" by "employeeObject"

    ReplyDelete
  11. To make this tutorial work:
    1. The last "form.jsp" example file should be (re)named: "edit.jsp", simply because it's the edit page.
    2. Add the "database.properties" file to your "src/main/resources" folder. This file is placed in your classpath when you build your webapp. It should contain the following config items (used in the "spring-config.xml"):
    - database.driver=com.mysql.jdbc.Driver
    - database.url=jdbc:mysql://localhost:3306/springhibernate_db
    - database.user=YOUR_USERNAME
    - database.password=YOUR_PASSWORD
    - hibernate.show_sql=true

    Offcourse, change the values to your needs...
    Hope this helps you JavaGuys!

    Roald Koning

    ReplyDelete
  12. Oh and by the way... for updating your existing employee by the "edit.jsp" registerForm you should add: "" within your form tags. Without this (hidden) input field hibernate can't update the employee because the id is unknown.

    Roald Koning

    ReplyDelete
  13. Add: form:input path="id" value="${employeeObject.id}" type="hidden". Of course within tags ^^

    Roald Koning

    ReplyDelete
  14. I am getting below exception

    org.springframework.beans.factory.BeanDefinitionStoreException: Unexpected exception parsing XML document from ServletContext resource [/WEB-INF/spring-config.xml]; nested exception is javax.xml.parsers.FactoryConfigurationError: Provider for javax.xml.parsers.DocumentBuilderFactory cannot be found

    ReplyDelete
  15. SEVERE: Servlet.service() for servlet [mvc-dispatcher] in context with path [/SampleSpringMaven] threw exception [Request processing failed; nested exception is org.hibernate.hql.internal.ast.QuerySyntaxException: employee is not mapped [from employee]] with root cause
    org.hibernate.hql.internal.ast.QuerySyntaxException: employee is not mapped


    could anyone please help on this

    ReplyDelete
  16. Check you're hibernate-blahblah.hbm mapping the issue must be there. if u not using xml mapping check your model class if u have mapped the id to your field. Lastly...check if you have the correct database

    ReplyDelete
  17. This comment has been removed by the author.

    ReplyDelete
  18. HTTP Status 500 - Servlet.init() for servlet mvc-dispatcher threw exception

    type Exception report

    message Servlet.init() for servlet mvc-dispatcher threw exception

    description The server encountered an internal error that prevented it from fulfilling this request.

    exception

    javax.servlet.ServletException: Servlet.init() for servlet mvc-dispatcher threw exception
    org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
    org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
    org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
    org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
    org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
    org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
    org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
    java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    java.lang.Thread.run(Thread.java:745)

    root cause

    org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping#0': Invocation of init method failed; nested exception is org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [com.beingjavaguys.dao.DataDaoImpl] for bean with name 'dataDaoImpl' defined in ServletContext resource [/WEB-INF/spring-config.xml]; nested exception is java.lang.ClassNotFoundException: com.beingjavaguys.dao.DataDaoImpl
    Related cause: org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [com.beingjavaguys.dao.DataDaoImpl] for bean with name 'dataDaoImpl' defined in ServletContext resource [/WEB-INF/spring-config.xml]; nested exception is java.lang.ClassNotFoundException: com.beingjavaguys.dao.DataDaoImpl
    Related cause: org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [com.beingjavaguys.services.DataServiceImpl] for bean with name 'dataServiceImpl' defined in ServletContext resource [/WEB-INF/spring-config.xml]; nested exception is java.lang.ClassNotFoundException: com.beingjavaguys.services.DataServiceImpl

    i m facing above error plz help me i m new with spring mvc

    thanks in advance.

    ReplyDelete
  19. Hi, in the pom.xml you have added so many dependencies. Can you explain the significance of each dependency, for actual hibernate exactly how many and which all dependencies are requried

    ReplyDelete
    Replies
    1. Hi, i think most of the dependencies included are pretty obvious, like mysql, hibernate, spring, log4j for logs etc...the exclusion part excludes dependencies you dont want. For the ones you dont understand, check out the maven repo they have some sort of decumentation there.... mvnrepository.com

      Delete
  20. Hi, can you post a Spring hibernate one to many or many to many crud example. Just like this tutorial, you'll have really helped me. Thanks, great tutorial

    ReplyDelete
  21. if any one wants to try the same application with Oracle pls add followinf dependency in pom.xml



    com.oracle
    ojdbc6
    11.2.0.1.0

    ReplyDelete
  22. Can you please share all your project files.

    ReplyDelete
  23. Hi, thanks for your tutorial, I'm doing it and it works, but my question is in the combobox. I need to load a combobox dynamically. To do this I have the following:

    @RequestMapping(value = "form", method = RequestMethod.GET)
    public ModelAndView getForm(@ModelAttribute("command") Table table,
    BindingResult result) {
    Map model = new HashMap();
    model.put("table", tableService.getTableList());
    return new ModelAndView("form", model);
    }
    In my JSP I have:


    option value="-1">Select Data /option

    option value="${table.idData}" ${table.nameData} /option



    And the result is that it gives me the combobox, the equivalent to the number of data in the table spaces, but does not show any data. Can you help me with this?

    ReplyDelete
  24. Thanks for great job! Can you help me to add a "Search" button to your CRUD example. "Search" button searches user for example by name.

    ReplyDelete
  25. add this code in edit.jsp page it can resolve editing problems

    ReplyDelete





















  26. com.healthcare.eopd.webapp.model.User





    org.hibernate.dialect.MySQLDialect
    true

    create












    /WEB-INF/pages/


    .jsp





    ReplyDelete
  27. @Entity
    public class User {
    /*@Autowired
    UserAddress userAddress;
    @Autowired
    UserContact userContact;*/

    @Id
    @GeneratedValue
    private int id;
    @Column(name = "userName")
    private String userName;

    @Column(name = "password")
    private String password;

    ReplyDelete





















  28. com.healthcare.eopd.webapp.model.User





    org.hibernate.dialect.MySQLDialect
    true

    create












    /WEB-INF/pages/


    .jsp






    ReplyDelete
  29. Hi there,

    Thanks for this great tutorial. I went through it and I am able to add a new user to the database. However, when I click to see the list of users I have a blank page. Could you please help.

    Joel.

    ReplyDelete
  30. Anonymous Peter20 June 2015 at 23:31

    Hi there,

    Thanks for this great tutorial. I went through it and I am able to add a new user to the database. However, when I click to see the list of users I have a blank page. Could you please help.

    Peter.

    ReplyDelete

Like Us on Facebook


Like Us On Google+



Contact

Email: neel4soft@gmail.com
Skype: neel4soft