We learned how to integrate Spring and Hibernate in our last tutorial. Today we will move forward and integrate Spring MVC and Hibernate frameworks in a web application CRUD example. Our final project structure looks like below image, we will look into each of the components one by one. Note that I am using Spring
4.0.3.Release
and Hibernate 4.3.5.Final
versions for our example, the same program is also compatible for Spring 4 and Hibernate 3, however you need to make small changes in spring bean configuration file discussed in the last tutorial.
Let’s look at all the maven dependencies are required for hibernate and spring MVC framework integration.
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="https://maven.apache.org/POM/4.0.0" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://maven.apache.org/POM/4.0.0 https://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.journaldev.spring</groupId>
<artifactId>SpringMVCHibernate</artifactId>
<name>SpringMVCHibernate</name>
<packaging>war</packaging>
<version>1.0.0-BUILD-SNAPSHOT</version>
<properties>
<java-version>1.6</java-version>
<org.springframework-version>4.0.3.RELEASE</org.springframework-version>
<org.aspectj-version>1.7.4</org.aspectj-version>
<org.slf4j-version>1.7.5</org.slf4j-version>
<hibernate.version>4.3.5.Final</hibernate.version>
</properties>
<dependencies>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${org.springframework-version}</version>
<exclusions>
<!-- Exclude Commons Logging in favor of SLF4j -->
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<!-- Hibernate -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${hibernate.version}</version>
</dependency>
<!-- Apache Commons DBCP -->
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<!-- Spring ORM -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<!-- AspectJ -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>${org.aspectj-version}</version>
</dependency>
<!-- Logging -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${org.slf4j-version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>${org.slf4j-version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${org.slf4j-version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.15</version>
<exclusions>
<exclusion>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
</exclusion>
<exclusion>
<groupId>javax.jms</groupId>
<artifactId>jms</artifactId>
</exclusion>
<exclusion>
<groupId>com.sun.jdmk</groupId>
<artifactId>jmxtools</artifactId>
</exclusion>
<exclusion>
<groupId>com.sun.jmx</groupId>
<artifactId>jmxri</artifactId>
</exclusion>
</exclusions>
<scope>runtime</scope>
</dependency>
<!-- @Inject -->
<dependency>
<groupId>javax.inject</groupId>
<artifactId>javax.inject</artifactId>
<version>1</version>
</dependency>
<!-- Servlet -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- Test -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.7</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-eclipse-plugin</artifactId>
<version>2.9</version>
<configuration>
<additionalProjectnatures>
<projectnature>org.springframework.ide.eclipse.core.springnature</projectnature>
</additionalProjectnatures>
<additionalBuildcommands>
<buildcommand>org.springframework.ide.eclipse.core.springbuilder</buildcommand>
</additionalBuildcommands>
<downloadSources>true</downloadSources>
<downloadJavadocs>true</downloadJavadocs>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.5.1</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
<compilerArgument>-Xlint:all</compilerArgument>
<showWarnings>true</showWarnings>
<showDeprecation>true</showDeprecation>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.2.1</version>
<configuration>
<mainClass>org.test.int1.Main</mainClass>
</configuration>
</plugin>
</plugins>
<finalName>${project.artifactId}</finalName>
</build>
</project>
Some of the dependencies above are included by STS (Spring Tool Suite) when I create Spring MVC project. Important dependencies above are spring-context, spring-webmvc, spring-tx, hibernate-core, hibernate-entitymanager and spring-orm. I am using Apache Commons DBCP for connection pooling, but in real life situations, most probably you have connection pooling done by the container and all we need is to provide the JNDI reference details to use. NOTE: I noticed that some of the readers are getting database connection issues. Notice that in my pom.xml, there is no database driver. That works for me because I have MySQL driver in tomcat lib directory and some DataSource connections configured with it. For any database connection related issues, either put the database driver in container lib or include that in pom.xml dependencies.
We need to plugin the spring framework in our web application, that is done by configuring Spring framework DispatcherServlet
as the front controller. Our web.xml file looks like below.
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="https://java.sun.com/xml/ns/javaee"
xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://java.sun.com/xml/ns/javaee https://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/root-context.xml</param-value>
</context-param>
<!-- Creates the Spring Container shared by all Servlets and Filters -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Processes application requests -->
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
Most of the part is boilerplate code, most important part is the spring context file location where we will configure our spring beans and services. If you want, you can change them according to your project requirements.
We are using JPA annotations in our entity bean class, however, we can also have a simple java bean and mapping details in the XML file. In that case, we need to provide mapping file details while configuring Hibernate SessionFactory in spring bean configurations.
package com.journaldev.spring.model;
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 bean with JPA annotations
* Hibernate provides JPA implementation
* @author pankaj
*
*/
@Entity
@Table(name="PERSON")
public class Person {
@Id
@Column(name="id")
@GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
private String name;
private String country;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
@Override
public String toString(){
return "id="+id+", name="+name+", country="+country;
}
}
Our entity bean maps to PERSON table in MySQL database, notice that I have not annotated “name” and “country” fields with @Column
annotation because they are of the same name. Below SQL script shows the table details.
CREATE TABLE `Person` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(20) NOT NULL DEFAULT '',
`country` varchar(20) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
We will create PersonDAO
interface to declare the methods that we will use in our project. Next, we will provide hibernate specific implementation for it.
package com.journaldev.spring.dao;
import java.util.List;
import com.journaldev.spring.model.Person;
public interface PersonDAO {
public void addPerson(Person p);
public void updatePerson(Person p);
public List<Person> listPersons();
public Person getPersonById(int id);
public void removePerson(int id);
}
Hibernate-specific DAO implementation looks like below.
package com.journaldev.spring.dao;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;
import com.journaldev.spring.model.Person;
@Repository
public class PersonDAOImpl implements PersonDAO {
private static final Logger logger = LoggerFactory.getLogger(PersonDAOImpl.class);
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sf){
this.sessionFactory = sf;
}
@Override
public void addPerson(Person p) {
Session session = this.sessionFactory.getCurrentSession();
session.persist(p);
logger.info("Person saved successfully, Person Details="+p);
}
@Override
public void updatePerson(Person p) {
Session session = this.sessionFactory.getCurrentSession();
session.update(p);
logger.info("Person updated successfully, Person Details="+p);
}
@SuppressWarnings("unchecked")
@Override
public List<Person> listPersons() {
Session session = this.sessionFactory.getCurrentSession();
List<Person> personsList = session.createQuery("from Person").list();
for(Person p : personsList){
logger.info("Person List::"+p);
}
return personsList;
}
@Override
public Person getPersonById(int id) {
Session session = this.sessionFactory.getCurrentSession();
Person p = (Person) session.load(Person.class, new Integer(id));
logger.info("Person loaded successfully, Person details="+p);
return p;
}
@Override
public void removePerson(int id) {
Session session = this.sessionFactory.getCurrentSession();
Person p = (Person) session.load(Person.class, new Integer(id));
if(null != p){
session.delete(p);
}
logger.info("Person deleted successfully, person details="+p);
}
}
Notice that I am not using Hibernate Transaction, that is because it will be taken care by Spring framework.
Here are our service classes that are using Hibernate DAO classes to work with Person objects.
package com.journaldev.spring.service;
import java.util.List;
import com.journaldev.spring.model.Person;
public interface PersonService {
public void addPerson(Person p);
public void updatePerson(Person p);
public List<Person> listPersons();
public Person getPersonById(int id);
public void removePerson(int id);
}
package com.journaldev.spring.service;
import java.util.List;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.journaldev.spring.dao.PersonDAO;
import com.journaldev.spring.model.Person;
@Service
public class PersonServiceImpl implements PersonService {
private PersonDAO personDAO;
public void setPersonDAO(PersonDAO personDAO) {
this.personDAO = personDAO;
}
@Override
@Transactional
public void addPerson(Person p) {
this.personDAO.addPerson(p);
}
@Override
@Transactional
public void updatePerson(Person p) {
this.personDAO.updatePerson(p);
}
@Override
@Transactional
public List<Person> listPersons() {
return this.personDAO.listPersons();
}
@Override
@Transactional
public Person getPersonById(int id) {
return this.personDAO.getPersonById(id);
}
@Override
@Transactional
public void removePerson(int id) {
this.personDAO.removePerson(id);
}
}
Notice that spring declarative transaction management is applied by using @Transactional
annotation.
Our DAO and Service classes are ready, it’s time to write our controller class that will take care of client requests and uses service classes to perform database specific operations and then returns the view pages.
package com.journaldev.spring;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.journaldev.spring.model.Person;
import com.journaldev.spring.service.PersonService;
@Controller
public class PersonController {
private PersonService personService;
@Autowired(required=true)
@Qualifier(value="personService")
public void setPersonService(PersonService ps){
this.personService = ps;
}
@RequestMapping(value = "/persons", method = RequestMethod.GET)
public String listPersons(Model model) {
model.addAttribute("person", new Person());
model.addAttribute("listPersons", this.personService.listPersons());
return "person";
}
//For add and update person both
@RequestMapping(value= "/person/add", method = RequestMethod.POST)
public String addPerson(@ModelAttribute("person") Person p){
if(p.getId() == 0){
//new person, add it
this.personService.addPerson(p);
}else{
//existing person, call update
this.personService.updatePerson(p);
}
return "redirect:/persons";
}
@RequestMapping("/remove/{id}")
public String removePerson(@PathVariable("id") int id){
this.personService.removePerson(id);
return "redirect:/persons";
}
@RequestMapping("/edit/{id}")
public String editPerson(@PathVariable("id") int id, Model model){
model.addAttribute("person", this.personService.getPersonById(id));
model.addAttribute("listPersons", this.personService.listPersons());
return "person";
}
}
Notice that I am using @Controller
annotation, so that Spring framework will treat it as a Controller class to handle client requests. Also I am using @Autowired
and @Qualifier
annotations for injecting PersonService
, we could have done it in the spring context xml file too. Recommended Read: Spring Bean Autowiring
Our services are ready, all we need is to wire them through spring bean configurations. Our root-context.xml file is empty, so we will look only into the servlet-context.xml file.
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="https://www.springframework.org/schema/mvc"
xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xmlns:beans="https://www.springframework.org/schema/beans"
xmlns:context="https://www.springframework.org/schema/context" xmlns:tx="https://www.springframework.org/schema/tx"
xsi:schemaLocation="https://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd
https://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
https://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd
https://www.springframework.org/schema/tx https://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<!-- DispatcherServlet Context: defines this servlet's request-processing
infrastructure -->
<!-- Enables the Spring MVC @Controller programming model -->
<annotation-driven />
<!-- Handles HTTP GET requests for /resources/** by efficiently serving
up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />
<!-- Resolves views selected for rendering by @Controllers to .jsp resources
in the /WEB-INF/views directory -->
<beans:bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
<beans:bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<beans:property name="driverClassName" value="com.mysql.jdbc.Driver" />
<beans:property name="url"
value="jdbc:mysql://localhost:3306/TestDB" />
<beans:property name="username" value="pankaj" />
<beans:property name="password" value="pankaj123" />
</beans:bean>
<!-- Hibernate 4 SessionFactory Bean definition -->
<beans:bean id="hibernate4AnnotatedSessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<beans:property name="dataSource" ref="dataSource" />
<beans:property name="annotatedClasses">
<beans:list>
<beans:value>com.journaldev.spring.model.Person</beans:value>
</beans:list>
</beans:property>
<beans:property name="hibernateProperties">
<beans:props>
<beans:prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect
</beans:prop>
<beans:prop key="hibernate.show_sql">true</beans:prop>
</beans:props>
</beans:property>
</beans:bean>
<beans:bean id="personDAO" class="com.journaldev.spring.dao.PersonDAOImpl">
<beans:property name="sessionFactory" ref="hibernate4AnnotatedSessionFactory" />
</beans:bean>
<beans:bean id="personService" class="com.journaldev.spring.service.PersonServiceImpl">
<beans:property name="personDAO" ref="personDAO"></beans:property>
</beans:bean>
<context:component-scan base-package="com.journaldev.spring" />
<tx:annotation-driven transaction-manager="transactionManager"/>
<beans:bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<beans:property name="sessionFactory" ref="hibernate4AnnotatedSessionFactory" />
</beans:bean>
</beans:beans>
dataSource bean is defined for org.apache.commons.dbcp.BasicDataSource
class for basic connection pooling. org.springframework.orm.hibernate4.LocalSessionFactoryBean
bean is used for Hibernate 4 SessionFactory. For Hibernate 3, you will find similar classes as org.springframework.orm.hibernate3.LocalSessionFactoryBean
and org.springframework.orm.hibernate3.AnnotationSessionFactoryBean
. One important point is that when we are depending on Spring framework for Hibernate Session management, we should not define hibernate.current_session_context_class
, otherwise, you will get a lot of session transaction-related issues. personDAO and personService beans are self understood. transactionManager bean definition for org.springframework.orm.hibernate4.HibernateTransactionManager
is required for Spring ORM to support hibernate session transaction management. For Hibernate 3, you will find similar class as org.springframework.orm.hibernate3.HibernateTransactionManager
. Spring uses AOP for transaction management, you can now relate it with @Transactional
annotation. Recommended Read: Spring AOP and Spring Transaction Management
Our last part of the application is the view page, notice the attributes added to Model in Controller handler methods, we will use them to create our view page. We will also use JSTL tags, spring core and spring form tags.
<%@ taglib uri="https://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="https://www.springframework.org/tags" prefix="spring" %>
<%@ taglib uri="https://www.springframework.org/tags/form" prefix="form" %>
<%@ page session="false" %>
<html>
<head>
<title>Person Page</title>
<style type="text/css">
.tg {border-collapse:collapse;border-spacing:0;border-color:#ccc;}
.tg td{font-family:Arial, sans-serif;font-size:14px;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:#ccc;color:#333;background-color:#fff;}
.tg th{font-family:Arial, sans-serif;font-size:14px;font-weight:normal;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:#ccc;color:#333;background-color:#f0f0f0;}
.tg .tg-4eph{background-color:#f9f9f9}
</style>
</head>
<body>
<h1>
Add a Person
</h1>
<c:url var="addAction" value="/person/add" ></c:url>
<form:form action="${addAction}" commandName="person">
<table>
<c:if test="${!empty person.name}">
<tr>
<td>
<form:label path="id">
<spring:message text="ID"/>
</form:label>
</td>
<td>
<form:input path="id" readonly="true" size="8" disabled="true" />
<form:hidden path="id" />
</td>
</tr>
</c:if>
<tr>
<td>
<form:label path="name">
<spring:message text="Name"/>
</form:label>
</td>
<td>
<form:input path="name" />
</td>
</tr>
<tr>
<td>
<form:label path="country">
<spring:message text="Country"/>
</form:label>
</td>
<td>
<form:input path="country" />
</td>
</tr>
<tr>
<td colspan="2">
<c:if test="${!empty person.name}">
<input type="submit"
value="<spring:message text="Edit Person"/>" />
</c:if>
<c:if test="${empty person.name}">
<input type="submit"
value="<spring:message text="Add Person"/>" />
</c:if>
</td>
</tr>
</table>
</form:form>
<br>
<h3>Persons List</h3>
<c:if test="${!empty listPersons}">
<table class="tg">
<tr>
<th width="80">Person ID</th>
<th width="120">Person Name</th>
<th width="120">Person Country</th>
<th width="60">Edit</th>
<th width="60">Delete</th>
</tr>
<c:forEach items="${listPersons}" var="person">
<tr>
<td>${person.id}</td>
<td>${person.name}</td>
<td>${person.country}</td>
<td><a href="<c:url value='/edit/${person.id}' />" >Edit</a></td>
<td><a href="<c:url value='/remove/${person.id}' />" >Delete</a></td>
</tr>
</c:forEach>
</table>
</c:if>
</body>
</html>
Just build and deploy the project into any servlet container of your choice, for example, Tomcat. Below screenshots shows the view pages for our application.
You will also find similar logs in the server log file.
Hibernate: insert into PERSON (country, name) values (?, ?)
INFO : com.journaldev.spring.dao.PersonDAOImpl - Person saved successfully, Person Details=id=15, name=Pankaj, country=USA
Hibernate: select person0_.id as id1_0_, person0_.country as country2_0_, person0_.name as name3_0_ from PERSON person0_
INFO : com.journaldev.spring.dao.PersonDAOImpl - Person List::id=10, name=Raman, country=UK2
INFO : com.journaldev.spring.dao.PersonDAOImpl - Person List::id=11, name=Lisa, country=France
INFO : com.journaldev.spring.dao.PersonDAOImpl - Person List::id=15, name=Pankaj, country=USA
This tutorial was aimed to provide sufficient details for you to getting started with Spring MVC and Hibernate integration, I hope you will find it useful. You can download the final project from below link and play around with it.
Download Spring MVC Hibernate Integration Project
You can also checkout the project from our GitHub Repository.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
I downloaded the project and deployed on jboss, not able to execute, please help
- John
Thanks for your reply pankaj, after adding in standalone.xml jboss waringin was suppressed but now i have another problem. Context initialization failed: org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘hibernate4AnnotatedSessionFactory’ defined in ServletContext resource [/WEB-INF/spring/appServlet/servlet-context.xml]: Invocation of init method failed; nested exception is java.lang.NoSuchMethodError: javax.persistence.Table.indexes()[Ljavax/persistence/Index; i googled and added asm.jar and cglib-nodep-2.1_3.jar but no use. please help thanks in advance
- john
please look into this ERROR [org.springframework.web.servlet.DispatcherServlet] (MSC service thread 1-4) Context initialization failed: org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘hibernate4AnnotatedSessionFactory’ defined in ServletContext resource [/WEB-INF/spring/appServlet/servlet-context.xml]: Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: javax/persistence/NamedStoredProcedureQuery
- john
Please help !! I got this error : Error An error has occurred Exception while loading the app : java.lang.Exception: java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: org.apache.catalina.LifecycleException: java.lang.ClassNotFoundException: com.journaldev.spring.dao.PersonDAOImpl
- Anas
can u plz draw the flow of the class digram as per the Spring MVC Hibernate MySQL Integration CRUD Example Tutorial , i am not able to understand how each of the calsses are connected to each other mainly service layer plz help me asap
- Asis
Are you able to execute the above code?
- micheal
Hi pankaj, Can you please help me. i am using the above code but i shows this HTTP Status 500 - Servlet.init() for servlet appServlet threw exception and i don’t know why i got this error.
- chitra
Hi pankaj, can you a post an example to edit multiple records at one shot and save it to database using spring mvc and hibernate.
- Murali
Why another example, you can extend this one to update multiple records in one go. All you need is small UI changes and Hibernate business logic changes to update multiple records.
- Pankaj
how to deploy the project? should I create a new meaven project and move all your files to run? waiting for your response!
- happin_boy
Just build the project using Maven command “mvn clean install” or use your IDE to export as WAR file and deploy in the container, here I am using tomcat.
- Pankaj
I have configured this project in eclipse.For running i am following: Run As–>Maven Build ::: clean install But build failing with below error: “Failed to execute goal org.apache.maven.plugins:maven-war-plugin:2.2:war (default-war) on project SpringHibernateWeb: Error assembling WAR: webxml attribute is required (or pre-existing WEB-INF/web.xml if executing in update mode) -> [Help 1]” I have web.xml at required place. Can you please advise as what I am missing?
- Naveen
I am getting the following error when i am using your code in Eclipse. java.lang.ClassNotFoundException: com.journaldev.spring.dao.PersonDAOImpl java.lang.ClassNotFoundException: com.journaldev.spring.service.PersonServiceImpl
- Kernelfreak
I got errors when trying to run it: org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from ServletContext resource [/WEB-INF/applicationContext.xml]; nested exception is java.io.FileNotFoundException: Could not open ServletContext resource [/WEB-INF/applicationContext.xml] at … … Caused by: java.io.FileNotFoundException: Could not open ServletContext resource [/WEB-INF/applicationContext.xml] do we need applicationContext.xml file?
- John Tsun
Hi,Pankaj, I am getting this one, when web page is loaded. HTTP Status 404 - type Status report message description The requested resource is not available. Apache Tomcat/7.0.55 WARN : org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/spring/] in DispatcherServlet with name ‘appServlet’ ************* Web.xml ********************* contextConfigLocation /WEB-INF/spring/root-context.xml org.springframework.web.context.ContextLoaderListener appServlet org.springframework.web.servlet.DispatcherServlet contextConfigLocation /WEB-INF/spring/appServlet/servlet-context.xml 1 appServlet /
- Santosh Shingare
I think you have forgot to include root-context.xml, if not, How to write root-context.xml
- Rizwan Mursaleen
Download the project, for some files where we don’t have anything Spring specific, I might have excluded them.
- Pankaj
I’m run this program on NetBeans IDE 8.0 , Whenever run this program problem is occuring like this: Severe: Exception while loading the app Severe: Undeployment failed for context /EMD Severe: Exception while loading the app : java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: org.apache.catalina.LifecycleException: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.jindal.emd.model.Person] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.web.bind.annotation.ModelAttribute(value=person)}
- Lokesh Kumar
I downloaded the project and successfully ran it after making a couple of bellow changes - 1. Import project in eclipse. (Any, i used eclipse) 2. Include MySql connector dependency in pom.xml file as it is missing there. mysql mysql-connector-java 5.1.32 3. Update Project Dependencies - RightClick On Project --> Maven --> Update 3. Change username and password properties in servlet-context.xml file according to yours. 4. Create DB with ‘testdb’ name. 5. Clean, compile and Install project by running bellow maven commands on the console. mvn clean compile, mvn install. 6. Run the project on tomcat server (You can use other server also but i have used tomcat.) 7. Application is ready at URL -
https://localhost:8080/SpringMVCHibernate/persons
Cheers.!! :)- Aatif
Hi Aatif, Thanks for the detailed comment, I missed adding MySQL Driver jar in project pom.xml file because it’s part of my Tomcat lib directory. In most of the real life scenarios, we use JNDI DataSource configured in the container and for that we need to have driver jars in the container lib directory. I hope it clarifies the confusion for anyone else facing the similar issue, i will keep it in mind for future tutorials and include jars in pom.xml dependencies.
- Pankaj
Hello Aatif I did everything that you said but still I am getting WARN : org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/spring/] in DispatcherServlet with name ‘appServlet’
- Sandeep
Hi, Pankaj i was facing problem even after changing all requirements like username and password created same database as u given in above example error is. HTTP Status 500 - Request processing failed; nested exception is org.springframework.transaction.CannotCreateTransactionException: Could not open Hibernate Session for transaction; nested exception is org.hibernate.exception.GenericJDBCException: Could not open connection. please help me as soon as possible. Thanks and Regards Gopalkrishna
- Gopalkrishna
You need to include the database driver, I have updated the post with this detail. You could also see the below comment from Aatif for the same.
- Pankaj
Thanks for doing this tutorial. I’d agree with Murali’s suggestion of an extra tutorial, showing changes to the controller and adding a second table to the model. Regards Alex
- Alex
Worked flawlessly for me. Thank you very much for taking the time to post this! Marq
- Marq W
Hello Pankaj, I too am getting the same errors as kernelfreak. Please can you advise us on how to resolve these issues? Many thanks.
- tammy
Hi Pankaj, I am looking programmatically and declarative transaction management (for hibernate and spring) example. Can you describe in a blog if one transaction get failed second transaction automatic get reverted. Thanks, Sandeep
- sandeep k
Hello Sundeep, Look at the below link . https://dtr-trading.blogspot.in/2014/02/spring-mvc-4-and-hibernate-4.html
- Hemanth
Hi Pankaj, Good Article. Suppose here, i have another class “Address” and if i want to implement “one-to-many” relationship here with person has multiple addresses. Mean while adding person, i want to add multiple addresses on above html form , so please help me to implement changes in above files.
- Sagar Mali
Pankaj, thanks for a wonderful and well explained article. Is there a way we can have a query which can get us a Person using name field and using the same DAO method structure ??
- Priya
I think you have forgot to include root-context.xml, if not, How to write root-context.xml
- Rizwan Mursaleen
Download the project, for some files where we don’t have anything Spring specific, I might have excluded them.
- Pankaj
I’m run this program on NetBeans IDE 8.0 , Whenever run this program problem is occuring like this: Severe: Exception while loading the app Severe: Undeployment failed for context /EMD Severe: Exception while loading the app : java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: org.apache.catalina.LifecycleException: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.jindal.emd.model.Person] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.web.bind.annotation.ModelAttribute(value=person)}
- Lokesh Kumar
I downloaded the project and successfully ran it after making a couple of bellow changes - 1. Import project in eclipse. (Any, i used eclipse) 2. Include MySql connector dependency in pom.xml file as it is missing there. mysql mysql-connector-java 5.1.32 3. Update Project Dependencies - RightClick On Project --> Maven --> Update 3. Change username and password properties in servlet-context.xml file according to yours. 4. Create DB with ‘testdb’ name. 5. Clean, compile and Install project by running bellow maven commands on the console. mvn clean compile, mvn install. 6. Run the project on tomcat server (You can use other server also but i have used tomcat.) 7. Application is ready at URL -
https://localhost:8080/SpringMVCHibernate/persons
Cheers.!! :)- Aatif
Hi Aatif, Thanks for the detailed comment, I missed adding MySQL Driver jar in project pom.xml file because it’s part of my Tomcat lib directory. In most of the real life scenarios, we use JNDI DataSource configured in the container and for that we need to have driver jars in the container lib directory. I hope it clarifies the confusion for anyone else facing the similar issue, i will keep it in mind for future tutorials and include jars in pom.xml dependencies.
- Pankaj
Hello Aatif I did everything that you said but still I am getting WARN : org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/spring/] in DispatcherServlet with name ‘appServlet’
- Sandeep
Hi, Pankaj i was facing problem even after changing all requirements like username and password created same database as u given in above example error is. HTTP Status 500 - Request processing failed; nested exception is org.springframework.transaction.CannotCreateTransactionException: Could not open Hibernate Session for transaction; nested exception is org.hibernate.exception.GenericJDBCException: Could not open connection. please help me as soon as possible. Thanks and Regards Gopalkrishna
- Gopalkrishna
You need to include the database driver, I have updated the post with this detail. You could also see the below comment from Aatif for the same.
- Pankaj
Thanks for doing this tutorial. I’d agree with Murali’s suggestion of an extra tutorial, showing changes to the controller and adding a second table to the model. Regards Alex
- Alex
Worked flawlessly for me. Thank you very much for taking the time to post this! Marq
- Marq W
Hello Pankaj, I too am getting the same errors as kernelfreak. Please can you advise us on how to resolve these issues? Many thanks.
- tammy
Hi Pankaj, I am looking programmatically and declarative transaction management (for hibernate and spring) example. Can you describe in a blog if one transaction get failed second transaction automatic get reverted. Thanks, Sandeep
- sandeep k
Hello Sundeep, Look at the below link . https://dtr-trading.blogspot.in/2014/02/spring-mvc-4-and-hibernate-4.html
- Hemanth
Hi Pankaj, Good Article. Suppose here, i have another class “Address” and if i want to implement “one-to-many” relationship here with person has multiple addresses. Mean while adding person, i want to add multiple addresses on above html form , so please help me to implement changes in above files.
- Sagar Mali
Pankaj, thanks for a wonderful and well explained article. Is there a way we can have a query which can get us a Person using name field and using the same DAO method structure ??
- Priya
create Why it not work? Hbiernate not create a table ((( Work only by using sql script.
- fix
hi Fix, I got the same problem. You should add the following line to the hibernate properties in the Spring configuration(xml) file. create
- Manjula
How about an example of Select queries with join conditions and more tables involved? basically a real time example would be ideal thanks in advance
- Abhi
Hi Pankaj, what is need of root-context.xml?
- Bikash
I am getting following error, Pls anyone help me to resolve this… org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException: Line 14 in XML document from ServletContext resource [/WEB-INF/spring/appServlet/servlet-context.xml] is invalid; nested exception is org.xml.sax.SAXParseException; lineNumber: 14; columnNumber: 23; cvc-complex-type.2.4.c: The matching wildcard is strict, but no declaration can be found for element ‘annotation-driven’.
- Vipul
And one more exception i have faced at the time of starting tomcat server… org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException: Line 18 in XML document from ServletContext resource [/WEB-INF/spring/appServlet/servlet-context.xml] is invalid; nested exception is org.xml.sax.SAXParseException; lineNumber: 18; columnNumber: 64; cvc-complex-type.2.4.c: The matching wildcard is strict, but no declaration can be found for element ‘resources’.
- Vipul
Hi, Pankaj. Awesome tutorial, helps me a lot, but could you please explain one thing. Why should we have “PersonService” interface, that in turn is exact copy of “PersonDAO”? Why can’t we just have “PersonServiceImpl” (with better name – “PersonService”). We already provide the layer of data access (“PersonDAO” and “PersonDAOImpl”), so why we need to create another redundant interface if we could use one class (in your case “PersonServiceImpl”) that can invoke interface methods? I hope, I’ve explained my point to you
- Sergey
Hi pankaj, I am getting the below error Caused by: java.lang.NoSuchMethodError: javax.persistence.Table.indexes()[Ljavax/persistence/Index; Please help.
- Hemanth
Hi pankaj, To fix below error i added below dependency org.hibernate.javax.persistence hibernate-jpa-2.1-api 1.0.0.Draft-6 But still getting the same error Caused by: java.lang.NoSuchMethodError: javax.persistence.Table.indexes()[Ljavax/persistence/Index; Please help.
- Hemanth
What is your java version. The issue seems to be with incompatible versions.
- Pankaj
Your Application Server is using JPA version 2.0 whereas you have built your application with JPA version 2.1. Thanks the problem.
- Mitesh Manani
Hi Pankaj, It’s java version 1.7
- Hemanth
Hi Pankaj, I am using java version 1.7 Please help
- Hemanth
in pom 4.2.8.Final or earlier
- vadym
When I do a maven build , I get the error :Fatal error compiling: tools.jar not found Plz help
- Suraj
I got the same problem also, it’s because your eclipse is pointing to a JRE Java version not a JDK. https://stackoverflow.com/questions/25185634/maven-build-failed-fatal-error-compiling-tools-jar-not-found
- Omunt
hi Pankaj, Thanks for the wonderful tutorials! I tried writing a SpringMVC-Hibernate application following this tutorial. Everything goes fine but i get an exception org.hibernate.HibernateException: No Session found for current thread when i try to do Session session = this.sessionFactory.getCurrentSession(); in DAOImpl class Execution goes fine without any exception if I replace it with Session session = this.sessionFactory.openSession(); I see we are not creating any session in the tutorial. How are we getting a session? Please explain. thanks in advance. -Rohit
- Rohit
We are getting the session from Spring ORM, as configured below. <beans:bean id=“hibernate4AnnotatedSessionFactory” class=“org.springframework.orm.hibernate4.LocalSessionFactoryBean”> Check this class source and you might find something causing the issue. What are the hibernate properties you are passing, is there any property named “thread”? Try removing that and check again.
- Pankaj
Thank you very much for tutorial. Almost all right! But when I start progect, i have an error 404 No mapping found for HTTP request with URI [/SpringMVCHibernate/] in DispatcherServlet, if I write by hands address /persons all is work! where I need to look. (In servlet-context.xml i change nothing ).
- Den
Waiting for youre answer
- Den
Sorry for late response, you need to understand URI. Since there is no home page defined, you get error if you go to web application home page. If you don’t want, just put index.html or any other welcome-page in web.xml to avoid this.
- Pankaj
How can be remove 404 error in detailed steps…
- Hero
Hi guys, I got the error in eclipse : org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/spring/] in DispatcherServlet with name ‘appServlet’ please help me how can resolve this problem. Thanks
- vaibhav
What is the content of root-context.xml
- Rikenson
You software does not respond anything, I have had a problem with error 404. tomcat não acusa erro, mas não existe retorno da pagina jsp.
- Daniel
tomcat does not accuse error, but there is no return of the jsp page.
- Daniel
Hi, I am newbie in spring, maven so sorry fir this basic question I try to implement your solution but in my context.xml I got this error: No setter found for property ‘sessionFactory’ in class … when I define the DAO bean. Same error with the service. here a part of my context.xml The little difference is that I externalized my DAO into a jar. com.domitik.domitikCDB.model.Box org.hibernate.dialect.MySQL5Dialect true the When I try to run my application I got this exception: 8:50:54.309 [localhost-startStop-1] ERROR o.s.web.context.ContextLoader - Context initialization failed org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘boxControllers’: Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.domitik.DomitikWS.services.BoxService com.domitik.DomitikWS.controllers.BoxControllers.boxService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.domitik.DomitikWS.services.BoxService] 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)} at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPost… Thanks for your help
- Shalom
Sorry some context.xml was truncated… com.domitik.domitikCDB.model.Box org.hibernate.dialect.MySQL5Dialect true the
- Shalom
DOESN’T FUNCTION. waste of time!!!
- Hamid
with some changes, which i don’t understand, it functioned. thanks anyway!!
- Hamid
Oct 04, 2019 3:59:15 PM org.apache.catalina.startup.Catalina start INFO: Server startup in 85420 ms Oct 04, 2019 4:00:07 PM org.hibernate.engine.internal.StatisticalLoggingSessionEventListener end INFO: Session Metrics { 212238 nanoseconds spent acquiring 1 JDBC connections; 0 nanoseconds spent releasing 0 JDBC connections; 0 nanoseconds spent preparing 0 JDBC statements; 0 nanoseconds spent executing 0 JDBC statements; 0 nanoseconds spent executing 0 JDBC batches; 0 nanoseconds spent performing 0 L2C puts; 0 nanoseconds spent performing 0 L2C hits; 0 nanoseconds spent performing 0 L2C misses; 0 nanoseconds spent executing 0 flushes (flushing a total of 0 entities and 0 collections); 0 nanoseconds spent executing 0 partial-flushes (flushing a total of 0 entities and 0 collections) } Oct 04, 2019 4:00:07 PM org.apache.catalina.core.StandardWrapperValve invoke SEVERE: Servlet.service() for servlet [appServlet] 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 java.lang.UnsupportedOperationException: Not supported by BasicDataSource] with root cause java.lang.UnsupportedOperationException: Not supported by BasicDataSource at org.apache.commons.dbcp.BasicDataSource.getConnection(BasicDataSource.java:1062) at org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl.getConnection(DatasourceConnectionProviderImpl.java:139) at org.hibernate.internal.AbstractSessionImpl$NonContextualJdbcConnectionAccess.obtainConnection(AbstractSessionImpl.java:380) at org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.obtainConnection(LogicalConnectionImpl.java:228) at org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.getConnection(LogicalConnectionImpl.java:171) at org.hibernate.internal.SessionImpl.connection(SessionImpl.java:450) at org.springframework.orm.hibernate4.HibernateTransactionManager.doBegin(HibernateTransactionManager.java:450) at org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:373) at org.springframework.transaction.interceptor.TransactionAspectSupport.createTransactionIfNecessary(TransactionAspectSupport.java:447) at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:277) at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213) at com.sun.proxy.$Proxy28.listPersons(Unknown Source) at com.journaldev.spring.PersonController.listPersons(PersonController.java:29) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205) at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133) at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:97) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738) at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:967) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:901) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970) at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861) at javax.servlet.http.HttpServlet.service(HttpServlet.java:622) at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846) at javax.servlet.http.HttpServlet.service(HttpServlet.java:729) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:292) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207) at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79) at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:528) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1099) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:670) at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1520) at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1476) at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.lang.Thread.run(Unknown Source)
- srinivasulu
I have download this project and deployed it on Apache tomcat. It’s run perfectly but my question is that no need to add mysql-connector-java jar. Please answer me. Is there any support in any jar file which you had used in this demo?
- kailas
Oviously it’s needed for creating MySQLDB connection, i have this jar in server lib. So i dont need that in the project.
- Pankaj
Hi, I downloaded your code and imported it in my spring tool suite Aim: what i am trying to do: 1. create a spring mvc project in STS by the ready made default template 2. trying Integrate hibernate with it so that i can integrate hibernate by my self without copying any ready made projects Problem faced: As per your pom file i have included the two hibernate dependencies, 1 apache dbcp dependency, 1 spring orm dependency Now when i try to use annotations like @entity i get error because the javax.persistance is not present in my project. in your downloaded project there is hibernate-jpa-2.1-api-1.0.0.Final-sources.jar in your maven dependencies library but not in pom file. Did you add it externally? if yes then why not included in pom. Please explain the significance of all jars in downloaded project and dependencies in pom and why some jars are present in maven dependencies but not in pom.xml
- chetan choudhary
Hello Pankaj, I’ve tried your code and seem it doesnt work for me. There is error code, you can see it in the following : https://www.scribd.com/doc/252024844/Error Currently I’m using Netbeans 8.0.1, Apache Tomcat 8.0.9.0, what should I do? Thanks… Regards, Herry
- Herry
Hello, Where did you download the hibernate and sfl4j jars. The package’s dont match. I cant find one that does. Thank You
- Ty
Many thanks! Clear and concise and works well!
- Abiy
Hi, It is working in tomcat/webapps installation but not on Eclipse. In eclipse it doesnt give the below logs, that is the reason it is not starting up. Anyone any guess why?? Jan 13, 2015 10:37:55 PM org.apache.catalina.core.ApplicationContext log INFO: Initializing Spring root WebApplicationContext INFO : org.springframework.web.context.ContextLoader - Root WebApplicationContext: initialization started Also can anybody explain here how sessionFactory.getCurrentSession() is working in this application. No session was opened in it. Many many thanks in Advance . .
- Vikash
sty 22, 2015 12:43:32 PM org.apache.catalina.core.ApplicationContext log INFO: Closing Spring root WebApplicationContext sty 22, 2015 12:43:34 PM org.apache.catalina.core.ApplicationContext log INFO: No Spring WebApplicationInitializer types detected on classpath sty 22, 2015 12:43:34 PM org.apache.catalina.core.ApplicationContext log plz look into this INFO: Initializing Spring root WebApplicationContext sty 22, 2015 12:43:34 PM org.apache.catalina.core.ApplicationContext log INFO: Initializing Spring FrameworkServlet ‘appServlet’ sty 22, 2015 12:45:15 PM org.apache.catalina.core.ApplicationContext log INFO: Destroying Spring FrameworkServlet ‘spring’ sty 22, 2015 12:45:16 PM org.apache.catalina.core.ApplicationContext log INFO: No Spring WebApplicationInitializer types detected on classpath sty 22, 2015 12:45:16 PM org.apache.catalina.core.ApplicationContext log INFO: Initializing Spring FrameworkServlet ‘spring’
- Jarek
Too many ads… I am feeling lite bet uncomfortable. Many thanks! Clear and concise and works well!
- Gururaj
Empty root-context.xml was a source of errors, I’ve changed path in web.xml to “/WEB-INF/spring/appServlet/servlet-context.xml”. Also had a problem with deploying using Eclipse(number of jars should be added to classpath manually), so deploy manually or use maven. Last problem was that pom.xml doesn’t have a dependency for mysql jdbc driver.
- Andrew
Thank you very much :) It works now.
- Barstu
Hi Pankaj, It is nice and concise article. Can you please explain about the client side validation i.e JavaScript integration with Spring MVC?
- Purba
I need understand how to integrate : Hibernate , Spring MVC with MySQL in NetBeans. Is urgent, if someone have solution code, please send me.
- Arnaldo Vicente
Hi Pankaj, when I run your application locally, I got this exception
- Srikanth Vengala
Nice Article .it’s very simple to understand to spring mvc flow. Thank you Pankaj.
- abhay deva
This is realy good to undersstand spring MVC Web Flow. Thanks Pankaj
- Naveen
addPerson function in DAOImpl is not working for me. I tried below two different ways and both are working: 1. Session session = this.sessionFactory.getCurrentSession(); // or openSession() session.save(p); 2. Session session = this.sessionFactory.getCurrentSession(); Transaction tx = session.beginTransaction(); session.persist(p); tx.commit(); Please check at your end and change code in above DAO accordingly. It will help others.
- Vaibhav Mittal
Thanks a LOOOOT for this tutorial !!! It helped me so much! I tried a lot of others tutorials before, and none of them worked… I just added this in the pom.xml : mysql mysql-connector-java 5.1.32 And I modified the credentials in servlet-context.xml, and now everything is fine!! I saw in other tutorials that we can use java class instead of xml files for configuration, are you considering this solution for your projects ? Thanks again!
- Luna
Hello, Pankaj! Can you add Search button to your application? Search button is for searching person by name.
- zodiac
Great job my friend, thank you so much !
- someone
Hi Pankaj, I’m using Glassfish and I got this error : Error An error has occurred Exception while loading the app : java.lang.Exception: java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: org.apache.catalina.LifecycleException: java.lang.ClassNotFoundException: com.journaldev.spring.dao.PersonDAOImpl Please Help !!
- Anas
Hey! Thank you so much for this wonderful tutorial. Clear and concise. I will now try to integrate this with AngularJS or BackboneJS! For those people encountering database connection-related exceptions, just add mysql Maven dependency to your pom.xml ( I added version 5.1.32) Again. Thank you sir! Cheers from the Philippines!
- Jz
Friend’ve noticed that not told web.xml as every application should contain, I can explain why?
- Hernando
Very nice example. I am getting this error: WARN : org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/SpringMVCHibernate/] in DispatcherServlet with name ‘appServlet’ Give me solution.
- Sachin Parse
you have to call: /SpringMVCHibernate/persons
- Stefania
servlet / Try this
- aayush
Thank you very much, finally I found a working example connecting SpringMVC with Hibernate and Maven
- Osama
Hi Pankaj, I used your example but with two classes(book and review) instead of one (person) and I receive an error (below) if i have @Controlled annotation on both classes. If i delete it from one it works but it says No mapping found for HTTP request with URI [/BookReviewApp/] in DispatcherServlet with name ‘servlet’.
ERROR: org.springframework.web.servlet.DispatcherServlet - Context initialization failed 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 java.lang.IllegalStateException: Ambiguous mapping found. Cannot map 'reviewController' bean method public java.lang.String com.bookReview.app.ReviewController.editReview(int,org.springframework.ui.Model) to {[/edit/{id}],methods=[],params=[],headers=[],consumes=[],produces=[],custom=[]}: There is already 'bookController' bean method public java.lang.String com.bookReview.app.BookController.editBook(int,org.springframework.ui.Model) mapped.
Thank you, Serban- serban
Hi Pankaj, It was a great article… :) mysql connector dependency is missing in ur pom.xml …
- Santosh Sm
Hi Pankaj, Thanks for above given nice example. But i have one issue, when i try to start the tomcat 6.0 in STS. It gives this below given error:- can u help me for this (I am unable to start the Tomcat) java.lang.reflect.InvocationTargetException at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.apache.catalina.startup.Bootstrap.load(Bootstrap.java:261) at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:413) Caused by: java.lang.NoClassDefFoundError: org/apache/juli/logging/LogFactory at org.apache.tomcat.util.digester.Digester.(Digester.java:326) at org.apache.catalina.startup.Catalina.createStartDigester(Catalina.java:253) at org.apache.catalina.startup.Catalina.load(Catalina.java:474) at org.apache.catalina.startup.Catalina.load(Catalina.java:562) … 6 more Caused by: java.lang.ClassNotFoundException: org.apache.juli.logging.LogFactory at java.net.URLClassLoader.findClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) … 10 more Thanks.
- Manoj
Hi Pankaj, You are doing a tremendous job. Thanks a lot for all the CONTENT… Professional to professional bow from my side. Thanks, Venkat
- Venkat
Thanks pankaj sir. U r doing fantastic job for us.
- Ankush
Awesome stuff. Thanks bro.
- Suraj Singh
Another question…How do we know whether DB connected or not , any log messages for this? I am using Oracle 11g. Thanks…
- Prashant
Hi Pankaj, Could you please reply below query. 1).How do we know whether DB connected or not , any log messages for this? I am using Oracle 11g. 2)Below Exception
- Prashant
Hi Pankaj, When i am trying to execute the application its showing 404 error .Can you please help me out with this problem. Thanks in Advance, Mamtha
- Mamatha Gurram
Hi Pankaj Great work. Worked perfectly once i added the sql connectoe dependency. Thanks a lot fro your efforts.
- DEVIPRASAD HEGDE
Hi DeviPrasad, I used the same exact example, but im getting 404 error when i am running the application. Can you please help me. Thanks. Mamtha
- Mamatha Gurram
appServlet / This gives an error in mapping resource not found plz tell me about this problem
- Ravi Rajput
Thank you Pankaj for this wonderful tutorial. I imported the project to eclipse and did all the steps required as Aatif did. I got to the index.jsp where it says Click to enter. When I click I got the error of 404 resource not available. Please note this is the first time I’m trying spring, hibernate. Any help will be appreciated. Thanks
- Ashraf
Why do you use @Autowired(required=true) @Qualifier(value=“personService”) , and not PersonServiceImpl ?The personService is not only the interface ?
- Peter
Regarding the 404 errors that people are encountering, I found that I was hitting a 404 error when I was trying to run tomcat out of Eclipse. When I copy-pasted the project war file to the tomcat webapps folder and then ran tomcat from the command prompt, the web app functioned properly. So, my steps are as follows: 1. Run “mvn clean install” from the command prompt 2. Navigate to the folder that the war file was created in. In my case it was under the …/SpringMVCHibernate/target folder. The command prompt should say where the war file was created. 3. Copy-paste this war file to your tomcat webapps folder. In my case I keep it under C:\tools\apache-tomcat-7.0.62\webapps 4. Run tomcat from the command line. The command is “startup.bat”. This assumes you have the CATALINA_HOME system variable set up properly. The web app worked after this. Gave myself a headache trying to figure out what was wrong with my code.
- Derek
That was very helpful, what is the URL… localhost:8080/
- Dev
Thankss broo… :(
- Nilesh Vadaliya
Muy buenos post gracias, aprendemos mucho de tu trabajo sigue adelante compartiendo el conocimiento.
- Isaac
what is the url to execute this code?
- shikha srivastava
Good exposure, but not for spring fresher, a lot of jar files have to be added in project, so i suggest that you have to show an image of jar files in this tutorial, It would be great helpful, Thank you sir.
- Aabid Husain
Dear Sir, Very Good Tutorial. Please modify it to include Date of Birth property. Also use primefaces .Those will be very much helpful to newbies Thanks Raichand Ray
- Raichand Ray
Hello Sir, i am new to Spring and Hibernate. I want to integrate Spring 3.0 with Hibernate 3.2. But i do not have any idea how to do that. Sir if and only if possible can you provide me a simple example Spring with Hibernate using MVC architecture with annotation. Its humble request sir. Thank You.
- Shaikh Hussain
without maven.
- Shaikh Hussain
No mapping found for HTTP request with URI [/SpringMvcHibernate/] in DispatcherServlet with name ‘appServlet’
- Sachin
Thanks It works. As suggested above, changed the pom to include mysql connector . Created test db.
- Subramanya
Thank you for the CRUD example! I see you are using hidden form fields to maintain state of non-editable entity fields. Is there any other (recommended) way to create CRUD forms that only partially edit an entity? If that entity had, for instance, a BLOB field, it would not pass through the form as a hidden input element and would be lost upon every update, correct? How would you approach creating a form for such an entity? Thank you, Andrew
- Andrew
hai i couldnt your project… i have error WARN : org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/SpringMVCHibernate/] in DispatcherServlet with name ‘appServlet’ Why to resolved…? Thanks
- Adit
I imported using maven and run it works perfect. thanks
- Dair
it works for me. Nice article thank u sir .awesome tutorial website
- bala
Great tutorial, dude. Thanks a lot!
- Lucas
Hi Sir Please post a detailed answer for how to set welcome page as most of us are getting 404 error.
- guest
Nice tutorial. Thank you very much!
- Ilton
what happens if i want the same thing using two or more tables? i have to do the same twice?
- nacho
Awesome Example perfectly working…
- Rajesh
Hello I’m getting this error when i run the application: 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.journaldev.spring.dao.PersonDAOImpl] for bean with name ‘personDAO’ defined in ServletContext resource [/WEB-INF/spring/appServlet/servlet-context.xml]; nested exception is java.lang.ClassNotFoundException: com.journaldev.spring.dao.PersonDAOImpl Related cause: org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [com.journaldev.spring.dao.PersonDAOImpl] for bean with name ‘personDAO’ defined in ServletContext resource [/WEB-INF/spring/appServlet/servlet-context.xml]; nested exception is java.lang.ClassNotFoundException: com.journaldev.spring.dao.PersonDAOImpl Related cause: org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [com.journaldev.spring.service.PersonServiceImpl] for bean with name ‘personService’ defined in ServletContext resource [/WEB-INF/spring/appServlet/servlet-context.xml]; nested exception is java.lang.ClassNotFoundException: com.journaldev.spring.service.PersonServiceImpl … i checked the servlet-context.xml but every thing is OK. what the problem ??
- Fakher Hakim
Thank you, its working for me. In model, person, table name is Person instead of PERSON (@Table(name=“PERSON”))
- albert
I followed your tutorial step-by-step, except used the names for my personal database table, and I’m getting an error (seems like a couple other people had the same issue with no resolution). Any help would be appreciated.
- Tom