Spring 4 MVC+Hibernate 4+MySQL+Maven integration example using annotations

In this tutorial , we will integrate Spring with Hibernate using annotation based configuration. We will develop a simple CRUD oriented web application containing a form asking user input, saving that input in MySQL database using Hibernate , retrieving the records from database and updating or deleting them within transaction, all using annotation configuration.

Testing part of this post is covered in detail in Next Post where we perform unit/integration test using TestNG, mockito, spring-test, DBUnit & H2 database. To know more about testing with TestNG in general, please refer our TestNG Tutorials.


Following technologies being used:

  • Spring 4.0.6.RELEASE
  • Hibernate Core 4.3.6.Final
  • validation-api 1.1.0.Final
  • hibernate-validator 5.1.3.Final
  • MySQL Server 5.6
  • Maven 3
  • JDK 1.7
  • Tomcat 8.0.21
  • Eclipse JUNO Service Release 2
  • TestNG 6.9.4
  • Mockito 1.10.19
  • DBUnit 2.2
  • H2 Database 1.4.187

Let’s begin.

Step 1: Create the directory structure

Following will be the final project structure:

SpringHibernate_img1

Let’s now add the content mentioned in above structure explaining each in detail.

Step 2: Update pom.xml to include required dependencies

<?xml version="1.0"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
	xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

	<modelVersion>4.0.0</modelVersion>
	<groupId>com.websystique.springmvc</groupId>
	<artifactId>SpringHibernateExample</artifactId>
	<packaging>war</packaging>
	<version>1.0.0</version>
	<name>SpringHibernateExample</name>

	<properties>
		<springframework.version>4.0.6.RELEASE</springframework.version>
		<hibernate.version>4.3.6.Final</hibernate.version>
		<mysql.connector.version>5.1.31</mysql.connector.version>
		<joda-time.version>2.3</joda-time.version>
		<testng.version>6.9.4</testng.version>
		<mockito.version>1.10.19</mockito.version>
		<h2.version>1.4.187</h2.version>
		<dbunit.version>2.2</dbunit.version>
	</properties>

	<dependencies>
		<!-- Spring -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${springframework.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>${springframework.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${springframework.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-tx</artifactId>
			<version>${springframework.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-orm</artifactId>
			<version>${springframework.version}</version>
		</dependency>

		<!-- Hibernate -->
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-core</artifactId>
			<version>${hibernate.version}</version>
		</dependency>

		<!-- jsr303 validation -->
		<dependency>
			<groupId>javax.validation</groupId>
			<artifactId>validation-api</artifactId>
			<version>1.1.0.Final</version>
		</dependency>
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-validator</artifactId>
			<version>5.1.3.Final</version>
		</dependency>

		<!-- MySQL -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>${mysql.connector.version}</version>
		</dependency>

      	<!-- Joda-Time -->		
		<dependency>
  			<groupId>joda-time</groupId>
  			<artifactId>joda-time</artifactId>
  			<version>${joda-time.version}</version>
  		</dependency>
		
		<!-- To map JodaTime with database type -->  		
  		<dependency>
    		<groupId>org.jadira.usertype</groupId>
    		<artifactId>usertype.core</artifactId>
    		<version>3.0.0.CR1</version>
		</dependency>

		<!-- Servlet+JSP+JSTL -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>3.1.0</version>
		</dependency>
		<dependency>
			<groupId>javax.servlet.jsp</groupId>
			<artifactId>javax.servlet.jsp-api</artifactId>
			<version>2.3.1</version>
		</dependency>
		<dependency>
		    <groupId>javax.servlet</groupId>
		    <artifactId>jstl</artifactId>
		    <version>1.2</version>
		</dependency>
		
		
		<!-- Testing dependencies -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>${springframework.version}</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.testng</groupId>
			<artifactId>testng</artifactId>
			<version>${testng.version}</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.mockito</groupId>
			<artifactId>mockito-all</artifactId>
			<version>${mockito.version}</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>com.h2database</groupId>
			<artifactId>h2</artifactId>
			<version>${h2.version}</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>dbunit</groupId>
			<artifactId>dbunit</artifactId>
			<version>${dbunit.version}</version>
			<scope>test</scope>
		</dependency>
		
	</dependencies>

	<build>
		<pluginManagement>
			<plugins>
				<plugin>
					<groupId>org.apache.maven.plugins</groupId>
					<artifactId>maven-compiler-plugin</artifactId>
					<version>3.2</version>
					<configuration>
						<source>1.7</source>
						<target>1.7</target>
					</configuration>
				</plugin>
				<plugin>
					<groupId>org.apache.maven.plugins</groupId>
					<artifactId>maven-war-plugin</artifactId>
					<version>2.4</version>
					<configuration>
						<warSourceDirectory>src/main/webapp</warSourceDirectory>
						<warName>SpringHibernateExample</warName>
						<failOnMissingWebXml>false</failOnMissingWebXml>
					</configuration>
				</plugin>
			</plugins>
		</pluginManagement>
		<finalName>SpringHibernateExample</finalName>
	</build>
</project>


First thing to notice here is the maven-war-plugin declaration. As we are using full annotation configuration, we don’t even include web.xml in our project, so we will need to configure this plugin in order to avoid maven failure to build war package. Since in this example we will use a form to accept input from user, we need also to validate the user input. We will choose JSR303 Validation here, so we have included validation-api which represents the specification, and hibernate-validator which represents an implementation of this specification. hibernate-validator also provides few of it’s own annotations (@Email, @NotEmpty, etc..) which are not part of the specification.

Along with that, we have also included JSP/Servlet/Jstl dependencies which we will be needing as we are going to use servlet api’s and jstl view in our code. In general, containers might already contains these libraries, so we can set the scope as ‘provided’ for them in pom.xml.

We also have added testing dependencies. Testing part of this post is described in detail in Next post.

Rest of the dependencies are for Spring, Hibernate and Joda-Time.

Step 3: Configure Hibernate

com.websystique.springmvc.configuration.HibernateConfiguration

package com.websystique.springmvc.configuration;

import java.util.Properties;

import javax.sql.DataSource;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@EnableTransactionManagement
@ComponentScan({ "com.websystique.springmvc.configuration" })
@PropertySource(value = { "classpath:application.properties" })
public class HibernateConfiguration {

    @Autowired
    private Environment environment;

    @Bean
    public LocalSessionFactoryBean sessionFactory() {
        LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
        sessionFactory.setDataSource(dataSource());
        sessionFactory.setPackagesToScan(new String[] { "com.websystique.springmvc.model" });
        sessionFactory.setHibernateProperties(hibernateProperties());
        return sessionFactory;
     }
	
    @Bean
    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(environment.getRequiredProperty("jdbc.driverClassName"));
        dataSource.setUrl(environment.getRequiredProperty("jdbc.url"));
        dataSource.setUsername(environment.getRequiredProperty("jdbc.username"));
        dataSource.setPassword(environment.getRequiredProperty("jdbc.password"));
        return dataSource;
    }
    
    private Properties hibernateProperties() {
        Properties properties = new Properties();
        properties.put("hibernate.dialect", environment.getRequiredProperty("hibernate.dialect"));
        properties.put("hibernate.show_sql", environment.getRequiredProperty("hibernate.show_sql"));
        properties.put("hibernate.format_sql", environment.getRequiredProperty("hibernate.format_sql"));
        return properties;        
    }
    
	@Bean
    @Autowired
    public HibernateTransactionManager transactionManager(SessionFactory s) {
       HibernateTransactionManager txManager = new HibernateTransactionManager();
       txManager.setSessionFactory(s);
       return txManager;
    }
}

@Configuration indicates that this class contains one or more bean methods annotated with @Bean producing beans manageable by spring container. In our case, this class represent hibernate configuration.
@ComponentScan is equivalent to context:component-scan base-package="..." in xml, providing with where to look for spring managed beans/classes.
@EnableTransactionManagement is equivalent to Spring’s tx:* XML namespace, enabling Spring’s annotation-driven transaction management capability.
@PropertySource is used to declare a set of properties(defined in a properties file in application classpath) in Spring run-time Environment, providing flexibility to have different values in different application environments.

Method sessionFactory() is creating a LocalSessionFactoryBean, which exactly mirrors the XML based configuration : We need a dataSource and hibernate properties (same as hibernate.properties). Thanks to @PropertySource, we can externalize the real values in a .properties file, and use Spring’s Environment to fetch the value corresponding to an item. Once the SessionFactory is created, it will be injected into Bean method transactionManager which may eventually provide transaction support for the sessions created by this sessionFactory.

Below is the properties file used in this post.
/src/main/resources/application.properties

jdbc.driverClassName = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/websystique
jdbc.username = myuser
jdbc.password = mypassword
hibernate.dialect = org.hibernate.dialect.MySQLDialect
hibernate.show_sql = true
hibernate.format_sql = true

Step 4: Configure Spring MVC

com.websystique.springmvc.configuration.AppConfig

package com.websystique.springmvc.configuration;

import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.websystique.springmvc")
public class AppConfig {
	
	@Bean
	public ViewResolver viewResolver() {
		InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
		viewResolver.setViewClass(JstlView.class);
		viewResolver.setPrefix("/WEB-INF/views/");
		viewResolver.setSuffix(".jsp");
		return viewResolver;
	}
	
	@Bean
	public MessageSource messageSource() {
	    ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
	    messageSource.setBasename("messages");
	    return messageSource;
	}
}

Again, @Configuration marks this class as configuration class as mentioned above & ComponentScan referes to package locations to find the associated beans.
@EnableWebMvc is equivalent to mvc:annotation-driven in XML.
Method viewResolver configures a view resolver to identify the real view.

In this post, we are working with form submission, validating user input (via JSR303 annotations). In case of validation failure, default error messages are shown.To override those default by your own custom [internationalized] messages from an external Message bundle [.properties file], we need to configure a ResourceBundleMessageSource. Method messageSource is there for same purpose. Notice the parameter provided (messages) to basename method. Spring will search for a file named messages.properties in application class path. Let’s add that file:

/src/main/resources/messages.properties

Size.employee.name=Name must be between {2} and {1} characters long
NotNull.employee.joiningDate=Joining Date can not be blank
NotNull.employee.salary=Salary can not be blank
Digits.employee.salary=Only numeric data with max 8 digits and with max 2 precision is allowed
NotEmpty.employee.ssn=SSN can not be blank
typeMismatch=Invalid format
non.unique.ssn=SSN {0} already exist. Please fill in different value.

Notice that above message follows a specific pattern

{ValidationAnnotationClass}.{modelObject}.{fieldName}

Additionally, based on specific annotation (e.g. @Size) you can also pass the arguments to these messages using {0},{1},..{i} indexes.

Step 5: Configure Initializer class

com.websystique.springmvc.configuration.AppInitializer

package com.websystique.springmvc.configuration;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

public class AppInitializer implements WebApplicationInitializer {

	public void onStartup(ServletContext container) throws ServletException {

		AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
		ctx.register(AppConfig.class);
		ctx.setServletContext(container);

		ServletRegistration.Dynamic servlet = container.addServlet(
				"dispatcher", new DispatcherServlet(ctx));

		servlet.setLoadOnStartup(1);
		servlet.addMapping("/");
	}

}

The content above resembles the content of web.xml as we are using the front-controller DispatherServler, assigning the mapping (url-pattern in xml) and instead of providing the path to spring configuration file(spring-servlet.xml) , here we are registering the Configuration Class.

UPDATE: Note that above class can be written even more concisely [and it’s the preferred way], by extending AbstractAnnotationConfigDispatcherServletInitializer base class, as shown below:

package com.websystique.springmvc.configuration;

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

	@Override
	protected Class<?>[] getRootConfigClasses() {
		return new Class[] { AppConfig.class };
	}
 
	@Override
	protected Class<?>[] getServletConfigClasses() {
		return null;
	}
 
	@Override
	protected String[] getServletMappings() {
		return new String[] { "/" };
	}

}

Step 6: Add Controller to handle the requests

Add the controller which will serve the GET and POST request.

com.websystique.springmvc.controller.AppController

package com.websystique.springmvc.controller;

import java.util.List;
import java.util.Locale;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.websystique.springmvc.model.Employee;
import com.websystique.springmvc.service.EmployeeService;

@Controller
@RequestMapping("/")
public class AppController {

	@Autowired
	EmployeeService service;
	
	@Autowired
	MessageSource messageSource;

	/*
	 * This method will list all existing employees.
	 */
	@RequestMapping(value = { "/", "/list" }, method = RequestMethod.GET)
	public String listEmployees(ModelMap model) {

		List<Employee> employees = service.findAllEmployees();
		model.addAttribute("employees", employees);
		return "allemployees";
	}

	/*
	 * This method will provide the medium to add a new employee.
	 */
	@RequestMapping(value = { "/new" }, method = RequestMethod.GET)
	public String newEmployee(ModelMap model) {
		Employee employee = new Employee();
		model.addAttribute("employee", employee);
		model.addAttribute("edit", false);
		return "registration";
	}

	/*
	 * This method will be called on form submission, handling POST request for
	 * saving employee in database. It also validates the user input
	 */
	@RequestMapping(value = { "/new" }, method = RequestMethod.POST)
	public String saveEmployee(@Valid Employee employee, BindingResult result,
			ModelMap model) {

		if (result.hasErrors()) {
			return "registration";
		}

		/*
		 * Preferred way to achieve uniqueness of field [ssn] should be implementing custom @Unique annotation 
		 * and applying it on field [ssn] of Model class [Employee].
		 * 
		 * Below mentioned peace of code [if block] is to demonstrate that you can fill custom errors outside the validation
		 * framework as well while still using internationalized messages.
		 * 
		 */
		if(!service.isEmployeeSsnUnique(employee.getId(), employee.getSsn())){
			FieldError ssnError =new FieldError("employee","ssn",messageSource.getMessage("non.unique.ssn", new String[]{employee.getSsn()}, Locale.getDefault()));
		    result.addError(ssnError);
			return "registration";
		}
		
		service.saveEmployee(employee);

		model.addAttribute("success", "Employee " + employee.getName() + " registered successfully");
		return "success";
	}


	/*
	 * This method will provide the medium to update an existing employee.
	 */
	@RequestMapping(value = { "/edit-{ssn}-employee" }, method = RequestMethod.GET)
	public String editEmployee(@PathVariable String ssn, ModelMap model) {
		Employee employee = service.findEmployeeBySsn(ssn);
		model.addAttribute("employee", employee);
		model.addAttribute("edit", true);
		return "registration";
	}
	
	/*
	 * This method will be called on form submission, handling POST request for
	 * updating employee in database. It also validates the user input
	 */
	@RequestMapping(value = { "/edit-{ssn}-employee" }, method = RequestMethod.POST)
	public String updateEmployee(@Valid Employee employee, BindingResult result,
			ModelMap model, @PathVariable String ssn) {

		if (result.hasErrors()) {
			return "registration";
		}

		if(!service.isEmployeeSsnUnique(employee.getId(), employee.getSsn())){
			FieldError ssnError =new FieldError("employee","ssn",messageSource.getMessage("non.unique.ssn", new String[]{employee.getSsn()}, Locale.getDefault()));
		    result.addError(ssnError);
			return "registration";
		}

		service.updateEmployee(employee);

		model.addAttribute("success", "Employee " + employee.getName()	+ " updated successfully");
		return "success";
	}

	
	/*
	 * This method will delete an employee by it's SSN value.
	 */
	@RequestMapping(value = { "/delete-{ssn}-employee" }, method = RequestMethod.GET)
	public String deleteEmployee(@PathVariable String ssn) {
		service.deleteEmployeeBySsn(ssn);
		return "redirect:/list";
	}

}

It’s a pretty straight-forward Spring based controller.@Controller indicates that this class is a controller handling the requests with pattern mapped by @RequestMapping.Here with ‘/’, it is serving as default controller.

Method listEmployees , annotated with @RequestMethod.GET, handling both the default URL ‘/’ as well as ‘/list’. It acts as handle for initial page of application, showing a list of existing employees.

Method newEmployee is handling the GET request for the new employee registration page, showing page backed by a model Employee object.

Method saveEmployee is annotated with @RequestMethod.POST, and will handle the form-submission POST requests for new employee registration (‘/new’). Notice the parameters and their orders in this method. @Valid asks spring to validate the associated object(Employee). BindingResult contains the outcome of this validation and any error that might have occurred during this validation. Notice that BindingResult must come right after the validated object else spring won’t be able to validate and an exception been thrown. In case of validation failure, custom error messages(as we have configured in step 4) are shown.

We have also included code to check for SSN uniqueness as it is declared to be unique in database. Before saving/updating an employee, we are checking if the SSN is unique.If not, we generate validation error and redirect to registration page. This peace of code demonstrate a way to
fill it custom errors outside the validation framework as well while still using internationalized messages.

Method editEmployee takes you to registration page with employee details filled in, while updateEmployee gets called when you click on update button after possible updation on gui.

Method deleteEmployee is handling the deletion of an employee by it’s SSN number. Notice @PathVariable , which indicates that this parameter will be bound to variable in URI template (SSN in our case).

As for as Annotation based configuration goes,this is all we need to do. Now to make the application complete, we will add service layer, dao layer, views, Domain object, sample database schema and run the application.

Step 7: Add DAO Layer

com.websystique.springmvc.dao.AbstractDao

package com.websystique.springmvc.dao;

import java.io.Serializable;

import java.lang.reflect.ParameterizedType;

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

public abstract class AbstractDao<PK extends Serializable, T> {
	
	private final Class<T> persistentClass;
	
	@SuppressWarnings("unchecked")
	public AbstractDao(){
		this.persistentClass =(Class<T>) ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[1];
	}
	
	@Autowired
	private SessionFactory sessionFactory;

	protected Session getSession(){
		return sessionFactory.getCurrentSession();
	}

	@SuppressWarnings("unchecked")
	public T getByKey(PK key) {
		return (T) getSession().get(persistentClass, key);
	}

	public void persist(T entity) {
		getSession().persist(entity);
	}

	public void delete(T entity) {
		getSession().delete(entity);
	}
	
	protected Criteria createEntityCriteria(){
		return getSession().createCriteria(persistentClass);
	}

}

This Generic class is the base class for all DAO implementation classes. It provides the wrapper methods for common hibernate operations.
Notice above, that SessionFactory we have created earlier in step 3, will be autowired here.

com.websystique.springmvc.dao.EmployeeDao

package com.websystique.springmvc.dao;

import java.util.List;

import com.websystique.springmvc.model.Employee;

public interface EmployeeDao {

	Employee findById(int id);

	void saveEmployee(Employee employee);
	
	void deleteEmployeeBySsn(String ssn);
	
	List<Employee> findAllEmployees();

	Employee findEmployeeBySsn(String ssn);

}

com.websystique.springmvc.dao.EmployeeDaoImpl

package com.websystique.springmvc.dao;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import com.websystique.springmvc.model.Employee;

@Repository("employeeDao")
public class EmployeeDaoImpl extends AbstractDao<Integer, Employee> implements EmployeeDao {

	public Employee findById(int id) {
		return getByKey(id);
	}

	public void saveEmployee(Employee employee) {
		persist(employee);
	}

	public void deleteEmployeeBySsn(String ssn) {
		Query query = getSession().createSQLQuery("delete from Employee where ssn = :ssn");
		query.setString("ssn", ssn);
		query.executeUpdate();
	}

	@SuppressWarnings("unchecked")
	public List<Employee> findAllEmployees() {
		Criteria criteria = createEntityCriteria();
		return (List<Employee>) criteria.list();
	}

	public Employee findEmployeeBySsn(String ssn) {
		Criteria criteria = createEntityCriteria();
		criteria.add(Restrictions.eq("ssn", ssn));
		return (Employee) criteria.uniqueResult();
	}
}

Step 8: Add Service Layer

com.websystique.springmvc.service.EmployeeService

package com.websystique.springmvc.service;

import java.util.List;

import com.websystique.springmvc.model.Employee;

public interface EmployeeService {

	Employee findById(int id);
	
	void saveEmployee(Employee employee);
	
	void updateEmployee(Employee employee);
	
	void deleteEmployeeBySsn(String ssn);

	List<Employee> findAllEmployees(); 
	
	Employee findEmployeeBySsn(String ssn);

	boolean isEmployeeSsnUnique(Integer id, String ssn);
	
}

com.websystique.springmvc.service.EmployeeServiceImpl

package com.websystique.springmvc.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.websystique.springmvc.dao.EmployeeDao;
import com.websystique.springmvc.model.Employee;

@Service("employeeService")
@Transactional
public class EmployeeServiceImpl implements EmployeeService {

	@Autowired
	private EmployeeDao dao;
	
	public Employee findById(int id) {
		return dao.findById(id);
	}

	public void saveEmployee(Employee employee) {
		dao.saveEmployee(employee);
	}

	/*
	 * Since the method is running with Transaction, No need to call hibernate update explicitly.
	 * Just fetch the entity from db and update it with proper values within transaction.
	 * It will be updated in db once transaction ends. 
	 */
	public void updateEmployee(Employee employee) {
		Employee entity = dao.findById(employee.getId());
		if(entity!=null){
			entity.setName(employee.getName());
			entity.setJoiningDate(employee.getJoiningDate());
			entity.setSalary(employee.getSalary());
			entity.setSsn(employee.getSsn());
		}
	}

	public void deleteEmployeeBySsn(String ssn) {
		dao.deleteEmployeeBySsn(ssn);
	}
	
	public List<Employee> findAllEmployees() {
		return dao.findAllEmployees();
	}

	public Employee findEmployeeBySsn(String ssn) {
		return dao.findEmployeeBySsn(ssn);
	}

	public boolean isEmployeeSsnUnique(Integer id, String ssn) {
		Employee employee = findEmployeeBySsn(ssn);
		return ( employee == null || ((id != null) && (employee.getId() == id)));
	}
	
}

Most interesting part above is @Transactional which starts a transaction on each method start, and commits it on each method exit ( or rollback if method was failed due to an error). Note that since the transaction are on method scope, and inside method we are using DAO, DAO method will be executed within same transaction.

Step 9: Create Domain Entity Class(POJO)

Let’s create the actual Employee Entity itself whose instances we will be playing with in database.

com.websystique.springmvc.model.Employee

package com.websystique.springmvc.model;

import java.math.BigDecimal;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.Digits;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

import org.hibernate.annotations.Type;
import org.hibernate.validator.constraints.NotEmpty;
import org.joda.time.LocalDate;
import org.springframework.format.annotation.DateTimeFormat;

@Entity
@Table(name="EMPLOYEE")
public class Employee {

	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	private int id;

	@Size(min=3, max=50)
	@Column(name = "NAME", nullable = false)
	private String name;

	@NotNull
	@DateTimeFormat(pattern="dd/MM/yyyy") 
	@Column(name = "JOINING_DATE", nullable = false)
	@Type(type="org.jadira.usertype.dateandtime.joda.PersistentLocalDate")
	private LocalDate joiningDate;

	@NotNull
	@Digits(integer=8, fraction=2)
	@Column(name = "SALARY", nullable = false)
	private BigDecimal salary;
	
	@NotEmpty
	@Column(name = "SSN", unique=true, nullable = false)
	private String ssn;

	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 LocalDate getJoiningDate() {
		return joiningDate;
	}

	public void setJoiningDate(LocalDate joiningDate) {
		this.joiningDate = joiningDate;
	}

	public BigDecimal getSalary() {
		return salary;
	}

	public void setSalary(BigDecimal salary) {
		this.salary = salary;
	}

	public String getSsn() {
		return ssn;
	}

	public void setSsn(String ssn) {
		this.ssn = ssn;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + id;
		result = prime * result + ((ssn == null) ? 0 : ssn.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (!(obj instanceof Employee))
			return false;
		Employee other = (Employee) obj;
		if (id != other.id)
			return false;
		if (ssn == null) {
			if (other.ssn != null)
				return false;
		} else if (!ssn.equals(other.ssn))
			return false;
		return true;
	}

	@Override
	public String toString() {
		return "Employee [id=" + id + ", name=" + name + ", joiningDate="
				+ joiningDate + ", salary=" + salary + ", ssn=" + ssn + "]";
	}
	
}

This is a standard Entity class annotated with JPA annotations @Entity, @Table, @Column along with hibernate specific annotation @Type which we are using to provide mapping between database date type and Joda-Time LocalDate

@DateTimeFormat is a spring specific annotation which declares that a field should be formatted as a date time with a give format.

Rest of annotations are validation related (JSR303).Recall from step 4 that we have already provided the properties file(messages.properties) containing custom messages to be used in case of validation failure.

Step 10: Add Views/JSP’s

WEB-INF/views/allemployees.jsp [home page containing list of all existing employees]

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
	<title>University Enrollments</title>

	<style>
		tr:first-child{
			font-weight: bold;
			background-color: #C6C9C4;
		}
	</style>

</head>


<body>
	<h2>List of Employees</h2>	
	<table>
		<tr>
			<td>NAME</td><td>Joining Date</td><td>Salary</td><td>SSN</td><td></td>
		</tr>
		<c:forEach items="${employees}" var="employee">
			<tr>
			<td>${employee.name}</td>
			<td>${employee.joiningDate}</td>
			<td>${employee.salary}</td>
			<td><a href="<c:url value='/edit-${employee.ssn}-employee' />">${employee.ssn}</a></td>
			<td><a href="<c:url value='/delete-${employee.ssn}-employee' />">delete</a></td>
			</tr>
		</c:forEach>
	</table>
	<br/>
	<a href="<c:url value='/new' />">Add New Employee</a>
</body>
</html>

WEB-INF/views/registration.jsp [Registration page to create and save new employee in database]

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<html>

<head>
	<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
	<title>Employee Registration Form</title>

<style>

	.error {
		color: #ff0000;
	}
</style>

</head>

<body>

	<h2>Registration Form</h2>
 
	<form:form method="POST" modelAttribute="employee">
		<form:input type="hidden" path="id" id="id"/>
		<table>
			<tr>
				<td><label for="name">Name: </label> </td>
				<td><form:input path="name" id="name"/></td>
				<td><form:errors path="name" cssClass="error"/></td>
		    </tr>
	    
			<tr>
				<td><label for="joiningDate">Joining Date: </label> </td>
				<td><form:input path="joiningDate" id="joiningDate"/></td>
				<td><form:errors path="joiningDate" cssClass="error"/></td>
		    </tr>
	
			<tr>
				<td><label for="salary">Salary: </label> </td>
				<td><form:input path="salary" id="salary"/></td>
				<td><form:errors path="salary" cssClass="error"/></td>
		    </tr>
	
			<tr>
				<td><label for="ssn">SSN: </label> </td>
				<td><form:input path="ssn" id="ssn"/></td>
				<td><form:errors path="ssn" cssClass="error"/></td>
		    </tr>
	
			<tr>
				<td colspan="3">
					<c:choose>
						<c:when test="${edit}">
							<input type="submit" value="Update"/>
						</c:when>
						<c:otherwise>
							<input type="submit" value="Register"/>
						</c:otherwise>
					</c:choose>
				</td>
			</tr>
		</table>
	</form:form>
	<br/>
	<br/>
	Go back to <a href="<c:url value='/list' />">List of All Employees</a>
</body>
</html>

WEB-INF/views/success.jsp [Success page containg a confirmation of new employee creation and link back to list of employees]

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Registration Confirmation Page</title>
</head>
<body>
	message : ${success}
	<br/>
	<br/>
	Go back to <a href="<c:url value='/list' />">List of All Employees</a>
	
</body>

</html>

Step 11: Create Schema in database

CREATE TABLE EMPLOYEE(
	id INT NOT NULL auto_increment, 
	name VARCHAR(50) NOT NULL,
	joining_date DATE NOT NULL,
	salary DOUBLE NOT NULL,
	ssn VARCHAR(30) NOT NULL UNIQUE,
	PRIMARY KEY (id)
);

Please visit MySQL installation on Local PC in case you are finding difficulties in setting up MySQL locally.

Step 12: Build, deploy and Run Application

Now build the war (either by eclipse as was mentioned in previous tutorials) or via maven command line( mvn clean install). Deploy the war to a Servlet 3.0 container . Since here i am using Tomcat, i will simply put this war file into tomcat webapps folder and click on start.bat inside tomcat/bin directory.

If you prefer to deploy from within Eclipse using tomcat: For those of us, who prefer to deploy and run from within eclipse, and might be facing difficulties setting Eclipse with tomcat, the detailed step-by-step solution can be found at : How to setup tomcat with Eclipse.

Open browser and browse at http://localhost:8080/SpringHibernateExample/

Now click on “Add New Employee”, and click on Register button wihtout filling any detail:

Now fill the details

Click on Register, you should get something similar to:

Click on list to go to listing:
SpringHibernate_img6

Now add few records as before:

SpringHibernate_img7

Now click on delete link of Second record, it should get deleted.

SpringHibernate_img8
Now click on SSN link (which is an update) of 2nd record to update it:

SpringHibernate_img9
Now edit some fields, in addition change the SSN value to a value for an existing record:

SpringHibernate_img10

Try to update, you should get validation error on SSN:
SpringHibernate_img11

Fix that error by changing SSN to unique value, update, and then view complete list of records, update changes should be taken into account:

SpringHibernate_img12

Finally check the database at this moment :

SpringHibernate_img13

That’s it.

In the Next post, we will tests this application thoroughly with unit & integration tests, using TestNG, Mockito, DBUnit and testing best practices.

Download Source Code



References

If you like tutorials on this site, why not take a step further and connect me on Facebook , Google Plus & Twitter as well? I would love to hear your thoughts on these articles, it will help me improve further our learning process.

If you appreciate the effort I have put in this learning site, help me improve the visibility of this site towards global audience by sharing and linking this site from within and beyond your network. You & your friends can always link my site from your site on www.websystique.com, and share the learning.

After all, we are here to learn together, aren’t we?

  • Pingback: Saab()

  • Pingback: free pc games download full version for windows 10()

  • Pingback: free download for windows 10()

  • Pingback: download.icon()

  • Pingback: free slots casino()

  • Pingback: movers in barrie()

  • Pingback: term papers()

  • Pingback: Dentist Bethnal green()

  • Pingback: בגדי הריון()

  • Pingback: 福井歯医者()

  • Feelik

    Project no working. I show error: “Deployed application at context path /safecityfull but context failed to start”

    P.S. Sorry for my English

  • Pingback: 福井歯医者()

  • Pingback: 福井歯医者()

  • Pingback: pc games free download full version for windows 7()

  • Pingback: pc games free download full version for windows 7()

  • Pingback: pc games free download for mac()

  • Pingback: free download for windows 8()

  • Pingback: pdr training()

  • Pingback: Rabbit Vibrators()

  • Vyacheslav

    Hello again!
    I am trying to implement a custom annotation @Unique for checking fields unique, and there is a problem.

    If I UnikueFieldValidator isValid method of pointing out the @Transactional, the session factory == null. If i put the @Transactional, the session factory is there, but it does not return the session.

    In what may be the problem, or there is a similartutorial, with the implementation of custom @Unique annotation?

    code:
    http://stackoverflow.com/questions/40844699/custom-annotation-unique-for-checking-fields-unique

    Thank you!

  • Pingback: legit work from home companies()

  • Pingback: motorcycle games for android()

  • Pingback: war games for android()

  • Pingback: Молодежка4сезон25серия26серия()

  • Pingback: adamo cpu processor()

  • Pingback: lastssadsafdsa()

  • Pingback: nighties()

  • Pingback: mdansby.com()

  • Pingback: controllalo()

  • Pingback: Silicone Vibrator()

  • Pingback: Anal Stimulation()

  • Pingback: weather()

  • Pingback: buy business database()

  • Pingback: mdansby()

  • Pingback: molodejka4seria25()

  • Pingback: how to get rid of lip herpes()

  • Pingback: kala jadoo()

  • Pingback: uk()

  • Pingback: kala jadoo()

  • Sarala Jaz

    https://uploads.disquscdn.com/images/64f97571191c135ad5a720aaa98f42d97a8662971bd67d0ca91a4553c453216f.png

    Hi!,

    I tried the application and it insert part is working fine for me. But I can’t display the passing object in the list jsp.
    As in the code I’m adding list object in to model.addAttribute(“employee”, “employee”); but when i tried to display it in the jsp file it doesn’t display. I have attached the image below and values display like that. Please help me!!!

    • websystique

      Hi Sarala, it seems that expresses are not being evaluated. Please include isELIgnored=false in your JSP [], should be fine.

  • Pingback: free pc 3d games download full version()

  • Pingback: car racing games for pc()

  • Pingback: big boss vibrator()

  • Pingback: pussy toy()

  • Pingback: download android games()

  • Pingback: download apk games()

  • Pingback: molodejka4sezon21seria21seria22seria23()

  • Pingback: molodezhka4sezon212223seriya()

  • Pingback: opportunity()

  • Pingback: Rabbit Vibrators()

  • Pingback: Trenda - Pop Culture, News, Entertainment()

  • Pingback: xml181120167()

  • Pingback: xml18112016()

  • Pingback: link2016()

  • Pingback: herpes vaccine 2013 latest updates()

  • Pingback: ISP()

  • Pingback: pc games free download for mac()

  • Pingback: European River Cruises()

  • Pingback: free slots for fun()

  • Muhammad Arslan Anjum
  • Pingback: penny auctions uk()

  • Pingback: televisions electronics()

  • Pingback: Buy Seals Online()

  • Pingback: STREAMING()

  • Pingback: Letras de canciones()

  • Pingback: インフルエンザ()

  • Pingback: Web Design Company Aberdeen()

  • Pingback: nipple chains()

  • Pingback: programas descargar para windows 8()

  • Pingback: the bunny vibrator()

  • Pingback: How does the mind work()

  • Pingback: Personality type test()

  • Pingback: Personality Test()

  • Pingback: free software download for pc()

  • Pingback: Radio Jahan()

  • Pingback: molodezhka4sezon17seriya18192()

  • Pingback: penis pump()

  • Pingback: mens sex toys()

  • Pingback: Gratis Descargar Para Windows()

  • Pingback: molodejka()

  • Pingback: Belladonna Pocket Pussy()

  • Pingback: Choice Hotels()

  • Pingback: vu plus()

  • Pingback: molodezhka4seria()

  • Pingback: Pet Friendly Hotels()

  • Pingback: Starwood Hotels()

  • Pingback: сталик ханкишиев()

  • Pingback: trumpnews()

  • Pingback: Drug rehabilitation()

  • Pingback: Drug and alcohol rehabilitation centers()

  • Pingback: Traveling agencies()

  • Pingback: istanbul real estate()

  • Pingback: 10 Minute Fat Loss Review()

  • Pingback: Toned In Ten Review()

  • Pingback: full software download for windows 7()

  • Pingback: free software download for pc()

  • Pingback: Las Vegas PRP Hair Treatment()

  • Pingback: Full body detox()

  • Pingback: TAXI DUBROVNIK()

  • Pingback: How to clean your system()

  • Pingback: Agentes de Seguros()

  • Vyacheslav

    Hi from Belarus.
    cool tutorial!
    but I get such problem. Can You tell me how to solve it?

    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
    http://image.prntscr.com/image/7d25dd371eca49ada809fcff8ce7a93a.png

    • websystique

      Hello Vyacheslav,

      Sorry for being late. Probably your database connection is not up.Could you please check if the connection-info specified in application.properties matches with your setup [MySQL].

      application.properties:

      jdbc.driverClassName = com.mysql.jdbc.Driver
      jdbc.url = jdbc:mysql://localhost:3306/websystique
      jdbc.username = myuser
      jdbc.password = mypassword
      hibernate.dialect = org.hibernate.dialect.MySQLDialect
      hibernate.show_sql = true
      hibernate.format_sql = true

      Also please make sure that database itself is up and running. If you have issue with MySQL setup itself, Setup MySQLlocally will help you.

      • Vyacheslav

        thanks for the comment.
        the problem was in my hands curves. I pulled up poorly compatible Dependance.

        p.s. I read your cool tutorials with pleasure! :)

  • Pingback: Free Software Download For Windows 7()

  • Pingback: What is Scientology()

  • Pingback: best selling books()

  • Pingback: FREE Personality Test()

  • Pingback: best gspot vibrator()

  • Pingback: werewolf()

  • Pingback: best gspot vibrator()

  • Pingback: cat food()

  • Pingback: David Miscavige()

  • Pingback: home decor()

  • Pingback: cut resistant gloves()

  • Pingback: http://drjaydani.com/()

  • Pingback: Flat Belly Fast DVD Review()

  • Pingback: Diy Home Energy System Review()

  • Pingback: Happy()

  • Pingback: Basic Human Rights()

  • Pingback: Human Rights()

  • Pingback: Riding vibrator()

  • Pingback: anal sex toys()

  • Pingback: online sex toy()

  • Pingback: Fingerbang()

  • Pingback: dual stimulator()

  • Pingback: scam website()

  • Pingback: T-shirts Factory()

  • Pingback: computer repair()

  • Pingback: viagra()

  • Pingback: funny pictures()

  • https://www.linkedin.com/in/juanmf juanmf

    Hi, nice post!!

    But I’m getting a jar, unless I use `mvn war:war` (note: I removed templating and put necessary blocks tu create a REST API)

    Thanks!
    Juan

    • websystique

      Hi Juan, That is bizzare. In the pom.xml , we did include [war].If you don’t have it, by default it will generate a Jar.

  • Pingback: make money working from home()

  • Pingback: bono sin deposito apuestas()

  • Lalchand Mali

    localhost:8080/HrSolution/register.do when i give this url , it is not hitting controller

    Thanks in advance for help

    • websystique

      Hi, In this post, we have specified [ In AppInitializer] the mapping as ‘/’ [servlet.addMapping("/");]. And for your case you should have a corresponding mapping in controller for ‘/register’, and then try it.

  • Pingback: Université;()

  • Pingback: recycle()

  • Pingback: prefab houses prices()

  • Pingback: Egyptian Cotton bath towels()

  • Pingback: Gossip Lanka Hot News()

  • Pingback: Handyshop Innsbruck Hall()

  • Pingback: wood phone case()

  • Pingback: how the brain works()

  • Pingback: what is the brain()

  • Pingback: Gate Motor()

  • Pingback: doktor.strendj.online.kino.()

  • Pingback: aisti.online.smotret.aisti.mult()

  • Pingback: mir.dikogo.zapada.ceria.sezon()

  • Pingback: bookfra()

  • Pingback: インフルエンザ()

  • Pingback: インフルエンザ()

  • Pingback: インフルエンザ()

  • Pingback: esta página()

  • Pingback: blu ray player()

  • Pingback: stay at home mom jobs()

  • Pingback: プラセンタ()

  • Pingback: プラセンタ()

  • Pingback: プラセンタ()

  • Pingback: adenosine()

  • Pingback: agie charmilles()

  • Pingback: top2017bloomingme()

  • Pingback: jpmsru()

  • Pingback: Best Companies()

  • Pingback: retouche()

  • Pingback: online istikhara()

  • Pingback: Computer Repair Service()

  • Pingback: health-benefits-of-quinoa()

  • Pingback: bono sin deposito apuestas deportivas()

  • Pingback: kala jadu()

  • Pingback: recipes()

  • Pingback: casino()

  • Pingback: gaminator book of ra()

  • Pingback: imp source()

  • Pingback: jpmsruvideotoppornovideo()

  • Pingback: live in care()

  • Pingback: Fenster und Turen()

  • Pingback: Fenster()

  • Pingback: drama2016()

  • Pingback: find more()

  • Pingback: marketing automation()

  • Pingback: 受注管理システム()

  • Pingback: Cash for cars melbourne()

  • Pingback: Denver office space for rent()

  • Pingback: Outdoor wood fired pizza oven mobile Pizza Party made in Italy()

  • Pingback: cork coasters()

  • Pingback: wedding fans()

  • Pingback: Motivfliesen()

  • Pingback: SEO services in Lahore()

  • Pingback: Miracle Pianist videos()

  • Pingback: kinoklub()

  • Michael Njoroge

    Cool tutorial. initially I had a problem with hibernate which i solved by changing its version as 4.3.11.Final .

  • Pingback: como fazer retrospectiva()

  • Pingback: computer repair omaha()

  • Pingback: Pinganillo()

  • Pingback: Contact- AtlantaPiano()

  • Pingback: Youtubemp3download3()

  • Pingback: light deprivation greenhouse()

  • Pingback: surviving military deployments in afghanistan()

  • Pingback: lava rock Veneers()

  • Pingback: wills and estates()

  • Pingback: anonymous()

  • Pingback: satta matka()

  • Pingback: make an app()

  • Pingback: useful source()

  • Pingback: Mens Divorce Law Firm()

  • Pingback: Play games online()

  • Pingback: Play online games()

  • Pingback: SEO services in Lahore()

  • Pingback: learn more()

  • Pingback: Click here()

  • Pingback: More information()

  • Pingback: SEO services in Lahore()

  • Pingback: e-mentoring()

  • Pingback: boots for army basic training()

  • Pingback: Auto Protection()

  • Pingback: visitare questo sito()

  • Pingback: Free PC games()

  • Pingback: Visit Website()

  • Pingback: Craig Lubitski()

  • Pingback: garage door screen()

  • Pingback: SATTA MATKA RESULT()

  • Pingback: satta matka()

  • Pingback: london()

  • Pingback: Latex Inks distributor()

  • Pingback: home improvement ideas()

  • Pingback: kala jadu()

  • Pingback: 注管理システム()

  • Pingback: black magic for love()

  • Pingback: sex toys()

  • Pingback: http://www.mypsychicadvice.com/()

  • Pingback: регистрация предприятия в киеве()

  • Pingback: Ottawa()

  • Pingback: how to make money on the internet()

  • goutam

    Hi,
    i am download this example and try to run but face this problem any one help me resolve the problem.

    Cannot change version of project facet Dynamic Web Module to 3.1.
    One or more constraints have not been satisfied.

    • goutam

      please help me any ………….please
      how can i post print screnn ?

      • websystique

        Hi Goutam, this is Eclise issue.Have a look at this link.

  • Pingback: french alps()

  • Pingback: TRAININGPAINTLESSDENTREPAIR.COM()

  • Pingback: WALLPAPERONFREE.COM()

  • Pingback: uk auction()

  • Pingback: how to find a work from home job()

  • Pingback: How To Determine the Sex of a Beaver()

  • Pingback: information()

  • Pingback: read more()

  • Pingback: taweez for love()

  • Pingback: http://www.hamefanim.co.il/()

  • Pingback: education()

  • Pingback: Home Security()

  • Pingback: saleforiphone()

  • Pingback: Home Automation()

  • Pingback: adult movies()

  • Pingback: Home Automation Florida()

  • Pingback: hydrochrome()

  • Mohammed AlRefaii

    Hello,
    Everything is working well but it saves to XML file not to Employee table in mysql DB,
    when i open Employee table its empty also i can save and retrieve data.
    is there an clarification for that please>

    • Mohammed AlRefaii

      I found the problem .. It was in mysql DB..
      its not set to commit so if i close workbench and open it again i find the new employee i saved them before.

  • Mohammed AlRefaii

    404 error is missing maven libraries so i solved it as flowing.

    Hello,
    first of all i would like to thank you for this amazing article,
    secondly i start to build Maven project and add everything manually with changing name of the project and name of the packages, and i am using separate Tomcat i export the war file then copy it to webapps folder in tomcat server. so i finished with 404 error.
    after that i downloaded the source code from you site and imported it to my eclipse then exported it as war file and copied it to tomcat webapps folder and everything was okay.
    so i searched a lot why my project didn’t work normally and i finished that my war file didn’t include maven lib files.
    so i open (Properties) for my project and in (Deployment Assembly) tab i added maven dependencies there and everything is okay now.
    BTW may be there is more than one reason to have 404 error .. but that what happened with me :)

    • websystique

      Hi, the step which you did are also mentioned in Setup tomcat with Eclipse.Yes i saw that you are using an external tomcat instance. Personally, i prefer to build everything on command line as i have zero trust in Eclipse during build and deploy, and then i deploy the war in external instance like you did. I did not come across this error unless the war was not complete or not properly deployed.Keep an eye and let me know if you face it again.

  • Pingback: gourmet hawaiian coffee()

  • Pingback: gourmet hawaiian coffee()

  • Pingback: gourmet hawaiian coffee()

  • Pingback: gourmet hawaiian coffee()

  • Pingback: web design in pittsburgh()

  • Pingback: faire de la guitare()

  • Pingback: British citizenship()

  • Pingback: Hibernate One-To-One Unidirectional with Shared Primary Key (Annotation) - WebSystique()

  • Pingback: Spring Security 4 Hello World Annotation+XML Example - WebSystique()

  • Pingback: hawaiian kona coffee()

  • Pingback: dabjars()

  • Pingback: skypepsyxologmoskvakiev()

  • Pingback: Turen()

  • Pingback: satta matka()

  • Pingback: free online phone number for receiving texts()

  • Pingback: vcc mastercard and visa card buy()

  • Pingback: buy tactical flashlights()

  • Pingback: life insurance lawyer()

  • Pingback: wholesale oakley sunglasses()

  • Martin Baccino

    Which entity works as the EntityManager?
    Thanks in advance.

    • websystique

      Hi Martin, This example is based on Hibernate SessionFactory and Session. EntityManager EntityManagerFacoty are JPA compliant Interfaces , and Hibernate does implement them as well. So you may choose to use Hibernate SessionFactory/Session [without strict compliance to JPA2] or Hibernate as Pure JPA2 implementation, using EntityManagerFactory and EntityManager instead. For Pure JPA2 Example, Please have a look at Spring 4 MVC+JPA2+Hibernate Many-to-many-Example.You will like it.

      • Martin Baccino

        Thanks for your quick and complete reply.
        I really appretiate it.

  • Pingback: downtown tampa magazine()

  • Pingback: work from home options()

  • Pingback: best android box for xbmc()

  • Suvayan Ghosh

    i am getting 404 error ..resource not available please help sir

    • websystique

      Hi Suvayan, If yo

  • Pingback: CM150DY-12NF()

  • Pingback: Jaydani()

  • Pingback: free virtual mobile number for sms verification()

  • Pingback: 룸알바()

  • Pingback: Taxi Airport Innsbruck St. Anton()

  • Pingback: legit work from home job()

  • Pingback: buy 1 million youtube views()

  • Pingback: tubepatrolporn()

  • Pingback: toilehtml()

  • Pingback: sunnyleonelatest()

  • Pingback: sunnyleone()

  • Pingback: 福井脱毛()

  • Pingback: descargar kodi en español()

  • Pingback: gambling()

  • Pingback: Sql()

  • Pingback: vigra()

  • Pingback: dpboss()

  • Pingback: ТелефоновСамсунг2016()

  • Pingback: Лучшие фильмы2()

  • Pingback: Лучшие фильмы()

  • Pingback: tower garden plants()

  • Pingback: how to make quick money()

  • Pingback: mountain coffee classics()

  • Pingback: hqporn2016()

  • Pingback: porn video tube, hard porn, streaming porn, hq porn()

  • Pingback: friv()

  • Pingback: vacation()

  • Pingback: pet()

  • Pingback: Living & Travel()

  • Pingback: digital nomad()

  • Pingback: toys()

  • Pingback: Edecanes doble AA en Cancun()

  • Pingback: who builds container houses uk()

  • Pingback: Auto loan()

  • Pingback: tmj disorders Daytona beach()

  • Pingback: outdoor sets()

  • Pingback: find a boyfriend()

  • Pingback: pregnancy help()

  • Pingback: buy a house()

  • Pingback: home sale()

  • Pingback: have a peek at this web-site()

  • Pingback: Queen Hair Company()

  • Pingback: Boîte à cadeaux()

  • Pingback: Led faucet light()

  • Pingback: Boat Transport()

  • Pingback: Soft Tip Darts()

  • Pingback: Augsburg()

  • Pingback: Firmenaktien()

  • Pingback: HDKINOONLINE()

  • Pingback: Dairy farm accounting()

  • Pingback: Handydoktor()

  • Pingback: wildlife removal()

  • Pingback: upskirts porn videos()

  • Pingback: 皮克灵 买房()

  • Pingback: Computer repair service 32127()

  • Pingback: stainless steel coffee cup()

  • rushang patel

    Hi Websystique ,
    This was amazing tutorial but I got the following error in my console.
    org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘webController’: Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.aarush.springmvc.service.EmployeeService com.aarush.springmvc.controller.WebController.service;

    I have given Webcontroller name in place of AppController. Please find attached screenshot.

    • websystique

      Hi Rushang, sorry i missed you post.Seems you are missing some path in component-scan.

  • Pingback: app maker free()

  • Pingback: earn money online()

  • Pingback: Lie detector in Denver()

  • Pingback: illuziaobmana()

  • Pingback: gratis descargar()

  • Pingback: clean up crew()

  • Pingback: garden()

  • Pingback: programas descargar()

  • Pingback: kona-coffee-bean.com()

  • Pingback: best coffee()

  • Pingback: gourmet hawaiian coffee()

  • Pingback: كارفور()

  • Pingback: got paid()

  • Pingback: kmakehitz com()

  • Pingback: escort orlando()

  • Pingback: Maria Johnsen()

  • Pingback: oyunlar indir()

  • Pingback: e cig juice()

  • Pingback: Seo Norge()

  • Pingback: Buy Instagram Likes()

  • Pingback: try here()

  • Pingback: home health care, home care()

  • Pingback: free download()

  • Pingback: aquatic fish()

  • Pingback: hawaiian coffee()

  • Pingback: check that()

  • Pingback: www.coffee-beans-inc.com()

  • Pingback: best coffee inc()

  • Pingback: gourmet hawaiian coffee()

  • Pingback: gourmet kona coffee()

  • Pingback: IM 体育()

  • Pingback: clic()

  • Pingback: greek iptv()

  • Pingback: fukuidatumou()

  • Pingback: fukuidatumou()

  • Pingback: Piece Of Heaven()

  • Pingback: free slot games wheel of fortune()

  • Pingback: free slot games free spins()

  • Pingback: free slot s()

  • Pingback: free casino slot()

  • Pingback: clic here()

  • Pingback: Samsung repair()

  • Pingback: helou zis me()

  • Pingback: helou zis me()

  • Dilip Shukla

    One of the best example available on internet to start coding in spring hibernate.Thanks.

  • Pingback: E-commerce Solutions()

  • Pingback: Free stuff()

  • Pingback: ukraine girl kiev lviv 2016()

  • Pingback: ukraine girl kiev lviv()

  • Pingback: work from home 2016()

  • Pingback: house to buy()

  • Pingback: agen shobet()

  • Pingback: Web Wealth System()

  • Pingback: buy homes()

  • Pingback: open house()

  • Pingback: peaberry coffee()

  • Pingback: film()

  • Pingback: کرک آفیس 365()

  • Pingback: myprotein()

  • Pingback: car detailing san diego()

  • Pingback: more()

  • Pingback: coffee from kona()

  • Pingback: Learn()

  • Pingback: ExxonMobil Gift Cards()

  • zili nidhal

    I cound not add log4j to this project , in fact the project doesn’t read log4j.properties
    maby i have to add code in the class ‘AppConfig.java’
    do have this codes ?

    the errors that i have :

    log4j:WARN No appenders could be found for logger (org.springframework.web.servlet.DispatcherServlet).
    log4j:WARN Please initialize the log4j system properly.
    log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info

    • websystique

      hi Zili,sorry i missed your post but, better late than never. For logging, no you don’t have to add anything in config. I would encourage you to use SLF4J with Logback, commonly used logging interface in enterprises nowadays. You just have to include following in your pom.xml

      ch.qos.logback
      logback-classic
      1.1.7

      and then in classed where you need logging, you can declare a variable like:

      private static final Logger logger = LoggerFactory.getLogger(MyApplication.class);
      logger.info(“Hi {}”,name);

      An example can be found in this post.

  • zili nidhal

    I can not add “addResourceHandlers” to the class Appconfig

    I want to add CSS floder and resources floder for the Log4j

  • Pingback: bantningspiller()

  • Pingback: cummins software()

  • Pingback: fleet graphics()

  • Pingback: girne üniversitesi()

  • Pingback: Google()

  • Pingback: Ruksis780()

  • Pingback: wood crafting tools()

  • Pingback: http://www.konacoffeeinc.com()

  • Pingback: http://www.coffeefromkona.com()

  • Pingback: http://www.peaberrybean.com()

  • Pingback: Tarot()

  • Pingback: 아이폰 배경 화면()

  • Pingback: Google()

  • Pingback: Spring MVC 4 + Spring Security 4 + Hibernate Example - WebSystique()

  • Pingback: лучшие фильмы года 2016()

  • zili nidhal

    Browser can’t access/find relative resources like CSS, images and links

  • FaisalHyder

    Hi there, once again, your tutorials are very helping :) May the almighty Allah reward you for your kind work. :)

  • mariha noor

    Hello
    Where is table name used in the above program?

    • websystique

      Hi Mariha,

      We are using Hibernate, and in Hibernate we map the entities in java to tables in database, using @Entity+@Table as shown below:

      @Entity
      @Table(name=”EMPLOYEE”)
      public class Employee

      Here we are saying that Employee is an Entity which maps to Table EMPLOYEE in database.Hope it’s clear for you now.

  • mariha noor

    Someone please tell me where is table name used?

  • Pingback: лучшие фильмы 2016 2016 года список новые фильмы()

  • mariha noor

    hello
    how can i make changes for salary validation?
    Instead of 8 digits i want to update it to 11 digits.

  • zili nidhal

    hello I can’t change JER version to 1.7
    i’m using 1.5 version

    • websystique

      Hi, did you mean you are not able to change JRE version to 1.7. It should be straight-forward from within Eclipse using Project->Properties->Java Compiler/BuildPath.You can also use maven-compiler-plugin as shown in pom.xml here in this blog. In case you meant that you have to use JRE1.5, then you need to use tomcat 6 or lower.

  • hzms

    hello, is there any your tutorial about searching files through folder using spring and hibernate? Thank you in advance :)

  • FuSsA FyBy

    Hi websystique..

    i create an unique key:

    @Table( name = “EMPLOYEE”,
    uniqueConstraints = { @UniqueConstraint( columnNames = { “A”, “B”, “C” } ) } )
    public class Employee {
    //….
    }
    how can i add that to my /messages.properties, like u did with :

    non.unique.ssn= SSN {0} already exist.

  • zili nidhal

    what is the artifact Id that i have to use in this project
    I’m using java 1.8 and I can’t change version of project facet Dynamic Web Module to 3.1

  • Pingback: Дивергент, глава 3: За стеной / Allegiant, Высотка / High-Rise,()

  • Pingback: film online 2016 free ua ru kz()

  • Rufan Jobs

    Great Spring MVC tutorial, thanks for all!

  • Pingback: zootopia 2016()

  • Pingback: знакомства с Украинскими девушками()

  • Pingback: Spring 4 MVC+Hibernate Many-to-many JSP Example with annotation - WebSystique()

  • Pingback: Spring 4 MVC Form Validation and Resource Handling (Annotations) - WebSystique()

  • Pingback: rialudi()

  • Pingback: Java Spring 4 Hibenate 4 Crud Project - siberoloji.com()

  • Dileep Kumar Kottakota

    I am using oracle sql instead of mysql.
    I got struck at id not generating, so im getting sql excetion.
    So what i have to do solve this problem.

    • websystique

      Hi Dileep,

      Oracle does not support Identity. So following will not work on Oracle:

      @Id
      @GeneratedValue(strategy = GenerationType.IDENTITY)
      private int id;

      However, Oracle does support sequences. So you can create a sequence and use that one instead, like shown below:

      @Id
      @SequenceGenerator(name=”SEQ_GEN”, sequenceName=”MY_TABLE_SEQ”, allocationSize=1)
      @GeneratedValue(strategy=GenerationType.SEQUENCE, generator=”SEQ_GEN”)
      private int id;

      That means, you would also need a sequence on db level, like the following:

      create sequence MY_TABLE_SEQ
      minvalue 1
      maxvalue 9999999999999999999999999999
      start with 1
      increment by 1;

      Side note : You may prefer to use AUTO strategy, to be DB agnostic.

      @Id
      @GeneratedValue(strategy = GenerationType.AUTO)
      private int id;

      In this case, Hibernate [based on DB] will decide which strategy [IDENTITY,SEQUENCE, Others..] to use. For oracle in this case, Hibernate will use a global sequence named hibernate_sequence. Personally, i prefer to be specific and avoid AUTO, people don’t change database everyday in their application anyway.

  • Dileep Kumar Kottakota

    Thank you very much for your tutorial.
    I am getting null pointer exception.
    Added attachment see once and help me out.

    • websystique

      Hi, Seems your dao is not autowired in service class. Please make sure you have EmployeeDaoImpl annotated with Spring annotation [@Repository("employeeDao")].

  • morpheme

    Hi everyone,

    I spent hours trying to fix the following error:

    “HTTP Status 500 – Request processing failed; nested exception is org.hibernate.exception.SQLGrammarException: could not prepare statement
    Column “SSN” not found; SQL statement:
    delete from Employee where ssn = ? [42122-190]”

    The problem occured every time i was trying to delete one of the records. Part of the reason was the fact, that instead of MySql i tried to use H2 Database. With MySql everything was okay. Finally i realised that perhpas the choice of “createSQLQuery” method isn’t probably the best solution in this example.
    To deal with HQL without problems it’s better to use the method “createQuery”. Here’s how it looks:

    Query query = getSession().createQuery(“delete from Employee where ssn = :ssn”);
    query.setString(“ssn”, ssn);
    query.executeUpdate();

    Maybe someone will find it useful.

    P.S.
    Thank you for your work websystique. It’s a great tutorial!

    • websystique

      Hi, I completely agree with your remarks.Thanks.

  • FuSsA FyBy

    Hi, @websystique:disqus thanks for this tutorial..
    How can i generate tables in DB using hibernate ?

  • Lukasz Towarek

    Hi @@websystique:disqus , great job, Iam just struggling with a one issue… I have some experience with Spring but wanted to do a project java config, hibernate and some front end to start. I’ve managed to succesfully build the project but no matter what I do, I cant access an app in the browser. The maven build succeeds , I am running Tomcat7 from command line (same as maven), war is placed in tomcat/webapps/ location (I also deployed it using Tomcat gui , still the same ), application starts with no error, I can even see output from hibernate in console then http://localhost:8080/myapp/ returns 404 in a browser. I thought Ive messed something up for the first time as I was using the tutorial for a guidance/ skeleton of my app, so I’ve created new clean workspace and pretty much copied everything from your tutorial ensuring folders. files structure, etc are the same, and I am still getting this 404, soooo frustating! :) :) I can see and that its working on BE side but my eyes cant see it! ;) Thanks for any help…

    • websystique

      Hey Lukasz, sorry i missed your post, but better late than never.Are you still facing any issue?

    • https://www.linkedin.com/in/juanmf juanmf

      same here, 404..

  • JuanMarcos

    Hello websystique!!!
    I really appreciate your website and all of the really helpful content !! thanks a lot!
    I have one question, i hope you can help me with.
    I need to add two different data sources to a project I’m working on.
    I been using your examples as reference, so, i would like to ask for any suggestion.

    Thanks for taking time for reading, and for any help.

    • websystique

      Hi Juan, sorry i missed your message. In case you are still looking for some info, let me know.

      • JuanMarcos

        I would aprecciate if you can help me about this, any information will be apreciated. Thanks for Replying!

        • websystique

          Hi Juan,I looked into two configuring two different ds. For that setup, you would be configuring two different SessionFactory beans. That means you may need @Qualifier to help autowire the correct sessionFactory for getting the session.Apart from that, nothing will change.

  • Kabir Khan

    Hi, i am complete new guys in AbstractDao jpa hibernate. can you explain me How session open and close of fetching data or saving.
    2. How to confirm data is save or not in database then after we are providing message of successfully save data or not.

    Please sir help me.

    • websystique

      Hello Kabir, sorry i missed your post. In case you were still looking for the answers, here they are:

      1) Transaction : Transaction is the main actor here[look at @Transactional at service]. A transaction starts at method entry and ends when we exit, if some exception occurs, transaction gets rolled back.

      2) Session: sessionFactory.getCurrentSession() returns the current session [could well be the session associated to current thread]. On first call, it creates the session, and then on subsequent calls within the same transaction, it returns the same session. Once the transaction commits/rollbacks, session is detatched from the thread and closed. You don’t have to close them explicitly, hibernate does that for you. All the operations [save, fetch are performed on an open session].

      3) For your question on confirmation if data is saved or not, this task is under a transaction and if the transaction completes [commits], it is guranteed to be perform it’s intended job.

      4) Regarding AbstractDao generic syntax, it’s highly used pattern to specify [in one shot] both the type of primary key, and type of entity, hence saving you from specifying them on each and every operation.

      Hope it helps.

  • Khan

    First of all, Thanks a lot for the great tutorials. Now come to the problem.
    Here I’m implementing your code step by step, i mean first insertion then listing. Insertion is working fine but unable to list the records stored in database. I think Criteria criteria = createEntityCriteria();
    return (List) criteria.list();
    is not working.
    Checkout the code on github… https://github.com/khansquare/mvc.hibernate

  • Vamsi Krishna

    Hi to all,
    I am new to this site. I tried the above code with xml configuration. And i am getting following exception…

    Here I am able to get register page. When i try to save the data getting exception.

    java.lang.NoSuchMethodError: javax.el.ExpressionFactory.newInstance()Ljavax/el/ExpressionFactory;
    at org.hibernate.validator.internal.engine.messageinterpolation.InterpolationTerm.(InterpolationTerm.java:59)
    at org.hibernate.validator.messageinterpolation.ResourceBundleMessageInterpolator.interpolateExpression(ResourceBundleMessageInterpolator.java:341)
    at org.hibernate.validator.messageinterpolation.ResourceBundleMessageInterpolator.interpolateMessage(ResourceBundleMessageInterpolator.java:279)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:729)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:857)
    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
    at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
    at java.lang.Thread.run(Thread.java:722)

    Please help.

    The following is github location https://github.com/VamshiKrishna2828/SpringFormValidation.git

    Thank you.

    • websystique

      Hi Vamsi, Which tomcat version are you using? This is related to EL versions. Hibernate documentation referes to the problem you are getting. You may want to move to tomcat 7/8.

      • Vamsi Krishna

        Hi sir/madam,
        I have tried with all combinations by changing my tomcat version to tomcat 8. But I am not succeeded. Can you please check my code when you find time. The following is my project location in Github.

        https://github.com/VamshiKrishna2828/SpringFormValidation

        Thank you.

  • pall

    Hi..thank you so much for this wonderful tutorial. I am facing an issue while trying to run this application, “Requested resource is not availabe”. But i do not think my eclipse-tomcat set up is an issue because I have other projects which are running just fine with this setup. Also when I see the tomcat logs, I see the select query too as below. The MYSQL server version that Im using is 5.7. Please help me out with this issue.

  • Anil Vighne

    i am getting following error message if i am putting lazy attribute in my domain class (spring 4 +hibernate 4 integration )

    org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.anil.hibernate.pojo.Student.Course, no session or session was closed

    • websystique

      Hi Anil, Sorry i missed to reply your post. If you are using Lazy attribute, make sure to populate the collection within session[ use Hibernate.initialize(), some like shown in this post].

  • Pingback: Introduction to Spring MVC | k1025989's Mauro fortunatos e-Portfolio()

  • Dhyanandra Singh

    i tried this example and when i try to include custom css it throw error Resource interpreted as Stylesheet but transferred with MIME type text/html.

    i added some code in appConfig

    @Override

    public void addResourceHandlers(final ResourceHandlerRegistry registry) {

    registry.addResourceHandler(“/resources/**”).addResourceLocations(“classpath:/resources/theme1/”);

    }

    @Override

    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {

    configurer.enable();

    }

    • websystique

      Hi,
      you may want to look at this post where i’ve included custom CSS in application.

      • Dhyanandra Singh

        yes i developed my whole code same as your tutorial but css and js file not included on jsp i used

        <link type="text/css" href="” rel=”stylesheet”>

        and it shows an error in chrome console
        Resource interpreted as Stylesheet but transferred with MIME type text/html.

        • websystique

          Your resources folder with CSS/JS is inside webapp?

          • Dhyanandra Singh

            Thanks websystique for your assistance. project is working fine now.

  • Pingback: How do I convert from WebConfig.java to web.xml? - java()

  • Ksusha

    Hi, I used your project as example and created almost the same, but I can’t run it(((
    https://github.com/Ksushik/SpringMVC.git
    please, help me with that(
    when I browse at http://localhost:8080/SpringHibernateExample/ , Tomcat returns
    “No mapping found for HTTP request with URI [/SpringHibernateExample/] in DispatcherServlet with name ‘dispatcher’”
    I can’t understand why(
    I’ll appreciate, if somebody helps me, please) It drives me crazy )) Thank’s ahead )

    • websystique

      Hi Ksusha,

      Are you sure your modified project compiles and there is no other errors/exception when you are running it except the one you mentioned? For instance, @Autowired seems missing on transactionManager() in HibernateConfiguration. I do see that you did quite some refactoring. Anyway, in case you are running it with Eclipse+tomcat, please make sure that your tomcat is configured properly.You may want to look at Setup Tomcat with Eclipse. Keep me posted.

  • Subash Durairaj

    hi @websystique:disqus, I have tried this steps. but i am stuck in HibernateConfiguration.
    look like error message is “SessionFactory could not autowire” in transaction manager bean.
    can you help me please.

    • Subash Durairaj

      oops, forgot about it. i just register the hibernate configuration in the web initialize bean. error gone away. but however i am little bit confuse, i dont have anywhere a bean registration with type of SessionFactory type. then how its autowiring.? in hibernate configuration sessionFactory method return LocalSessionFactoryBean type, that is not a type of SessionFactory, then how its happen?
      Thanks

      • websystique

        Hi Subash,

        LocalSessionFactoryBean is a Factory bean implementing Spring FactoryBean interface, so it can produce the Beans of type SessionFactory. Do note that it produces only one object of type SessionFactory because it’s implementation of isSingleton returns true.

        Now, since our sessionFactory() Method is annotated with @Bean in @Configuration class, the returned object/bean of type LocalSessionFactoryBean is known to spring container. Anywhere we need an object of type SessionFactory, we ask for it to be injected using @Autowired, Spring knows it has a FactoryBean configured to produce this type of objects, it will in turn ask the Factory Bean (LocalSessionFactoryBean) to return the same shared instance of SessionFactory. LocalSessionFactoryBean will in turn use getObject() method & return the SessionFactory. Hope it clarifies your doubts.

        • Subash Durairaj

          gr8. thanks for your reply @websystique:disqus. now i understood how factory bean works, thanks.

  • Pingback: Spring MVC 4 FileUpload-Download Hibernate+MySQL Example - WebSystique()

  • Maciej

    I am sorry to bother you again but I am struggling
    with encoding problem.
    I would like to change it to UTF-8 in order to
    use Polish characters but my solution comes with strange result.

    If I leave the original jsp files:

    and

    I can save and retrieve objects with correct characters.
    Yet if I modify jsp pages:

    List of Employees łłłłóóóóó

    //the rest of the page

    The result will look something like this:

    List of
    Employees łłłłóóóóó

    Now if I switch all three ISO-8859-1 into UTF-8
    the opposite will happen.. the jsp content will show correctly but all objects
    will be saved with those strange (łłłłóó) characters.

    How can I modify this project the way both jsp and hibernate will accept all the
    characters??

    I have attached a screenshot to better describe the problem.

    Appreciate your help,
    Maciej

    • websystique

      Hi Maciej,

      If i understood correctly, you’ve already found the solution as you mentioned in another thread. Thanks for sharing, it will surely help others. I suppose you have tested your new code on all popular browsers [ Firefox, chrome & IE, optionally Safari].

      • Maciej

        Hi websystique,

        So far I have tested it on firefox and chrome and it runs smoothly. I believe I have also found a solution to the “facet project” error. Adding java version and updating war from 2.4 to 2.6 in pom.xml worked for me.

        org.apache.maven.plugins
        maven-compiler-plugin
        3.3

        1.7
        1.7

        org.apache.maven.plugins
        maven-war-plugin
        2.6

        src/main/webapp
        //the rest…

  • Maciej

    Hi,

    Can somebody help me on how to add transaction in this project.

    I got here:

    @Override

    public void saveList(List division) {

    Session session = getSession();

    Transaction tx =session.beginTransaction();

    // first delete all old records

    Query query = session.createSQLQuery(“delete from kamienica.division where id > 0″);

    query.executeUpdate();

    //second insert the new list

    for (int i = 0; i < division.size(); i++) {

    Division tmp = division.get(i);

    save(tmp);

    if (i % 20 == 0) {

    // 20, same as the JDBC batch size

    // flush a batch of inserts and release memory:

    session.flush();

    session.clear();

    }

    }

    tx.commit();

    session.close();

    }

    Yet I receive:

    org.hibernate.TransactionException: nested transactions not supported.

    Appreciate your help
    Maciej

    PS
    Thanks for this project. It helped me a lot

    • websystique

      Hi Maciej,
      Hibernate is right, because this post project is ALREADY transactional. Service class is annotated with @Transactional, thus all methods of service are transactional. And you access your dao using service, so complete call is already transactional. You don’t need to create additonal transaction again.

      • Maciej

        Thanks! :)

    • Maciej

      I think I found the solution. I have added to AppInitializer class these lines:

      FilterRegistration.Dynamic fr = container.addFilter(“encodingFilter”,

      new CharacterEncodingFilter());

      fr.setInitParameter(“encoding”, “UTF-8″);

      fr.setInitParameter(“forceEncoding”, “true”);

      fr.addMappingForUrlPatterns(null, true, “/*”);

      So far it works. I hope it will help others that got stuck on the same problem

      Regards,
      Maciej

      • websystique

        Hi Maciej, one question from my side :-). Did you update meta tag in JSP to refer to UTF-8? Or you left it with ISO-8859-1 and just included that filter with force-encoding? I think once you applied force encoding, meta tag should not make any difference. Correct me if i am wrong.

  • Serge

    Brilliant! Thanks a lot! I tried many examples and this one actually works and explanations are great!

  • Randall Biagi

    HI I loaded the downloaded source project into my setup:
    Spring Tool Suite Ver 3.7.2.RELEASE on
    Eclipse Mars 4.5.1
    Spring Framework 4.2.3.RELEASE
    tomcat 8.0.30
    Commons-logging 1.2
    maven 3.3.9

    When I try to deploy to tomcat, I get this error in the Problems window:

    Cannot change version of project facet Dynamic Web Module to 3.1

    I was building another demo, and it was running perfectly up until the point where I loaded the validation jars. I then got this same error. and it broke the build.

    Any idea what the issue is, and how I can configure to get around it? Thanks!

    • websystique

      Hi Randall,

      This is just eclipse idiosyncrasy. You are not alone who faced this error in Eclipse [may be a good reason why people start liking intelliJ]. If you want to get rid of that, please take a look at this link. Let me know if you still face any issue.

      • Randall Biagi

        Thanks for the reply. As it turns out, it was partially operator error: When I first set up my dev environment, the version of maven that I installed was an earlier version. Then I downloaded the latest version to update my environment, but forgot that i needed to update my Windows System Environment variable for M2_HOME. So when I changed parameters in the new maven environment, I was actually modifying the original one. Oops. (Lights on , but nobody home… :-P) Fixing this and updating my maven project solved the problem for the demo project that I was originally working on (which led me down this path in the first place.) Now the validation code works in it. But it has not fully solved the issue with the websystique demo app, for some reason. When I run that, and try to browse to http://localhost:8080/SpringHibernateExample/, the server console is telling me the following:

        java.lang.IllegalArgumentException: Invalid character (CR or LF) found in method name
        at org.apache.coyote.http11.AbstractNioInputBuffer.parseRequestLine(AbstractNioInputBuffer.java:228)

        not certain what to do about this one yet…but definitely making progress…got any thoughts about this one?

        Thanks!

        • websystique

          Haven’t heard before of that one. BTW, which tomcat version are you using?
          Did you try to run first with the environment/versions mentioned in this post?

  • kiran

    i download the application and run on tomcat server when i deploy then i got following error

    HTTP Status 404 – /SpringHibernateExample/

    type Status report

    message /SpringHibernateExample/

    description The requested resource is not available.

    Can you guys help me to avoiding error

    • websystique

      Hi Kiran,

      Probably you are trying to run this from within Eclipse on integrated tomcat instance. Issue is probably that your Tomcat+Eclipse setup is not configured fully. I would suggest you to read Setup Tomcat with Eclipse. Let me know if you face any other issue.

      • kiran

        yes i am using eclipse and in that i configure tomcat 7 is it fine for that application tomcat 7 or i need to download tomcat 8

        • websystique

          No you don’t.But make sure to configure your tomcat properly as mentioned in the post i’ve shared.

          • kiran

            thanks for giving me suggestion i reslove this problem but when i run this application i got following error

          • websystique

            You still have problem in your project setup. And the screenshot you shared is incomplete. I can see that EmployeeService Bean was not even created which caused AppController to fail as it depends on that. But what caused EmployeeService to fail, would be present in your complete screenshot.

            Did you make any changes in the project after downloading it?

            May i ask you to perform >mvn clean install on this project using cmd-line and deploy the war to an external tomcat instance and let me know if you are successful?

          • yasirshabbir44

            I have face similar problem and didn’t change any thing after download / import

          • websystique

            Hi Yasir,
            Same as i asked to Kiran , could you please make sure that your local tomcat+Eclipse setup is fine. You can follow Setup Tomcat with Eclipse for the same.

          • yasirshabbir44

            Actually I am using Intellij instead Eclipse ..
            Yes It’s working fine on other project but I facing problem on this project?

          • websystique

            As mentioned in exception, please configure your project resources so that application.properties should be on found on class path.

          • yasirshabbir44

            org.springframework.beans.factory.BeanDefinitionStoreException: Failed to load bean class: com.websystique.springmvc.configuration.AppConfig; nested exception is java.io.FileNotFoundException: class path resource [application.properties] cannot be opened because it does not exist

          • ozeksi

            Make sure you have a db server up and running. Also dont forget “Create Schema in database” step. I solved my problem in this way. Good luck

  • Pawan Kalyan

    thanks..

  • Andi

    Just a note for Oracle users: To get this running with Oracle:

    - in pom.xml, remove the mysql dependency and add:

    com.oracle
    ojdbc6
    11.2.0.4.0

    - in application.properties, use:

    jdbc.driverClassName=oracle.jdbc.driver.OracleDriver
    jdbc.url=jdbc:oracle:thin:@your.oracle.host:1521:your-Oracle-SID

    - in Employee.java, for the id column, use:

    @GeneratedValue(strategy=GenerationType.AUTO)

    - In Step 11, create the table and also a sequence because Orcale has no “auto_increment”:

    CREATE TABLE employee (
    id INT NOT NULL,
    name VARCHAR2(50) NOT NULL,
    joining_date DATE NOT NULL,
    salary number(10) NOT NULL,
    ssn VARCHAR2(30) NOT NULL UNIQUE,
    primary key (id)
    );
    CREATE SEQUENCE hibernate_sequence;

    - hth, Andi

    • websystique

      Thanks for sharing it Andy.

  • Fakher Hakim

    Thank you for this Tutorial. i just want to know why you choosed to configure hibernate in a java class instead of an XML file ?

    • websystique

      Hi, XML configuration ‘to put simply’ is a thing of PAST. For the new projects, annotation based configuration is preferred (for already some years now) which keeps the thing short and concise. I found it easy to understand and manage compare to XML configuration.

  • JLopez Mostro

    hello… i need change jsp with jsf…

  • bmarkham

    Hi, what if I just want the registration process? I just want someone to enter their info and gets stored in a database. How would I go about that?

    • websystique

      Hi, But that’s what we are doing here. If you just want to save details and then move to a different view, return that view name from controller methods(SaveEmployee). Let me know if i misunderstood you.

      • bmarkham

        No you understood me. Since I am very new to this, I didn’t know if I just took the code that only saves new users into a database that it would screw up somehow.

  • Anuj Kumar Tarun

    here is console log

    Oct 12, 2015 9:10:57 AM org.springframework.web.context.ContextLoader initWebApplicationContext

    SEVERE: Context initialization failed

    org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [org.o7planning.dao.impl.DepartmentDAOImpl] for bean with name ‘departmentDAO’ defined in ServletContext resource [/WEB-INF/applicationContext.xml]; nested exception is java.lang.ClassNotFoundException: org.o7planning.dao.impl.DepartmentDAOImpl

    at org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1325)

    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.predictBeanType(AbstractAutowireCapableBeanFactory.java:594)

    at org.springframework.beans.factory.support.AbstractBeanFactory.isFactoryBean(AbstractBeanFactory.java:1394)

    at org.springframework.beans.factory.support.AbstractBeanFactory.isFactoryBean(AbstractBeanFactory.java:957)

    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:683)

    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:760)

    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)

    at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:403)

    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306)

    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106)

    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4797)

    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5291)

    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)

    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)

    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)

    at java.util.concurrent.FutureTask$Sync.innerRun(Unknown Source)

    at java.util.concurrent.FutureTask.run(Unknown Source)

    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)

    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)

    at java.lang.Thread.run(Unknown Source)

    Caused by: java.lang.ClassNotFoundException: org.o7planning.dao.impl.DepartmentDAOImpl

    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1713)

    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1558)

    at org.springframework.util.ClassUtils.forName(ClassUtils.java:247)

    at org.springframework.beans.factory.support.AbstractBeanDefinition.resolveBeanClass(AbstractBeanDefinition.java:395)

    at org.springframework.beans.factory.support.AbstractBeanFactory.doResolveBeanClass(AbstractBeanFactory.java:1346)

    at org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1317)

    … 19 more

    Oct 12, 2015 9:10:57 AM org.apache.catalina.core.StandardContext listenerStart

    SEVERE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener

    org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [org.o7planning.dao.impl.DepartmentDAOImpl] for bean with name ‘departmentDAO’ defined in ServletContext resource [/WEB-INF/applicationContext.xml]; nested exception is java.lang.ClassNotFoundException: org.o7planning.dao.impl.DepartmentDAOImpl

    at org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1325)

    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.predictBeanType(AbstractAutowireCapableBeanFactory.java:594)

    at org.springframework.beans.factory.support.AbstractBeanFactory.isFactoryBean(AbstractBeanFactory.java:1394)

    at org.springframework.beans.factory.support.AbstractBeanFactory.isFactoryBean(AbstractBeanFactory.java:957)

    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:683)

    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:760)

    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)

    at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:403)

    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306)

    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106)

    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4797)

    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5291)

    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)

    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)

    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)

    at java.util.concurrent.FutureTask$Sync.innerRun(Unknown Source)

    at java.util.concurrent.FutureTask.run(Unknown Source)

    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)

    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)

    at java.lang.Thread.run(Unknown Source)

    Caused by: java.lang.ClassNotFoundException: org.o7planning.dao.impl.DepartmentDAOImpl

    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1713)

    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1558)

    at org.springframework.util.ClassUtils.forName(ClassUtils.java:247)

    at org.springframework.beans.factory.support.AbstractBeanDefinition.resolveBeanClass(AbstractBeanDefinition.java:395)

    at org.springframework.beans.factory.support.AbstractBeanFactory.doResolveBeanClass(AbstractBeanFactory.java:1346)

    at org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1317)

    … 19 more

    Oct 12, 2015 9:10:57 AM org.apache.catalina.core.StandardContext startInternal

    SEVERE: Error listenerStart

    Oct 12, 2015 9:10:57 AM org.apache.catalina.core.StandardContext startInternal

    SEVERE: Context [/SpringHibernateExample] startup failed due to previous errors

    Oct 12, 2015 9:10:57 AM org.apache.catalina.core.ApplicationContext log

    INFO: Closing Spring root WebApplicationContext

    Oct 12, 2015 9:10:58 AM org.apache.coyote.AbstractProtocol start

    INFO: Starting ProtocolHandler ["http-bio-8080"]

    Oct 12, 2015 9:10:58 AM org.apache.coyote.AbstractProtocol start

    INFO: Starting ProtocolHandler ["ajp-bio-8009"]

    Oct 12, 2015 9:10:58 AM org.apache.catalina.startup.Catalina start

    INFO: Server startup in 4790 ms

  • Anuj Kumar Tarun

    I have downloaded the same application and trying to set-up in eclipse but i am getting many error any one can help me to find out error

    Oct 12, 2015 9:10:57 AM org.springframework.web.context.ContextLoader initWebApplicationContext

    SEVERE: Context initialization failed

    org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [org.o7planning.dao.impl.DepartmentDAOImpl] for bean with name ‘departmentDAO’ defined in ServletContext resource [/WEB-INF/applicationContext.xml]; nested exception is java.lang.ClassNotFoundException: org.o7planning.dao.impl.DepartmentDAOImpl

    at org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1325)

    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.predictBeanType(AbstractAutowireCapableBeanFactory.java:594)

    at org.springframework.beans.factory.support.AbstractBeanFactory.isFactoryBean(AbstractBeanFactory.java:1394)

    at org.springframework.beans.factory.support.AbstractBeanFactory.isFactoryBean(AbstractBeanFactory.java:957)

    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:683)

    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:760)

    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)

    at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:403)

    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306)

    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106)

    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4797)

    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5291)

    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)

    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)

    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)

    at java.util.concurrent.FutureTask$Sync.innerRun(Unknown Source)

    at java.util.concurrent.FutureTask.run(Unknown Source)

    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)

    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)

    at java.lang.Thread.run(Unknown Source)

    Caused by: java.lang.ClassNotFoundException: org.o7planning.dao.impl.DepartmentDAOImpl

    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1713)

    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1558)

    at org.springframework.util.ClassUtils.forName(ClassUtils.java:247)

    at org.springframework.beans.factory.support.AbstractBeanDefinition.resolveBeanClass(AbstractBeanDefinition.java:395)

    at org.springframework.beans.factory.support.AbstractBeanFactory.doResolveBeanClass(AbstractBeanFactory.java:1346)

    at org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1317)

    … 19 more

    Oct 12, 2015 9:10:57 AM org.apache.catalina.core.StandardContext listenerStart

    SEVERE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener

    org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [org.o7planning.dao.impl.DepartmentDAOImpl] for bean with name ‘departmentDAO’ defined in ServletContext resource [/WEB-INF/applicationContext.xml]; nested exception is java.lang.ClassNotFoundException: org.o7planning.dao.impl.DepartmentDAOImpl

    at org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1325)

    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.predictBeanType(AbstractAutowireCapableBeanFactory.java:594)

    at org.springframework.beans.factory.support.AbstractBeanFactory.isFactoryBean(AbstractBeanFactory.java:1394)

    at org.springframework.beans.factory.support.AbstractBeanFactory.isFactoryBean(AbstractBeanFactory.java:957)

    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:683)

    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:760)

    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)

    at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:403)

    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306)

    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106)

    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4797)

    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5291)

    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)

    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)

    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)

    at java.util.concurrent.FutureTask$Sync.innerRun(Unknown Source)

    at java.util.concurrent.FutureTask.run(Unknown Source)

    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)

    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)

    at java.lang.Thread.run(Unknown Source)

    Caused by: java.lang.ClassNotFoundException: org.o7planning.dao.impl.DepartmentDAOImpl

    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1713)

    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1558)

    at org.springframework.util.ClassUtils.forName(ClassUtils.java:247)

    at org.springframework.beans.factory.support.AbstractBeanDefinition.resolveBeanClass(AbstractBeanDefinition.java:395)

    at org.springframework.beans.factory.support.AbstractBeanFactory.doResolveBeanClass(AbstractBeanFactory.java:1346)

    at org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1317)

    … 19 more

    Oct 12, 2015 9:10:57 AM org.apache.catalina.core.StandardContext startInternal

    SEVERE: Error listenerStart

    Oct 12, 2015 9:10:57 AM org.apache.catalina.core.StandardContext startInternal

    SEVERE: Context [/SpringHibernateExample] startup failed due to previous errors

    Oct 12, 2015 9:10:57 AM org.apache.catalina.core.ApplicationContext log

    INFO: Closing Spring root WebApplicationContext

    Oct 12, 2015 9:10:58 AM org.apache.coyote.AbstractProtocol start

    INFO: Starting ProtocolHandler ["http-bio-8080"]

    Oct 12, 2015 9:10:58 AM org.apache.coyote.AbstractProtocol start

    INFO: Starting ProtocolHandler ["ajp-bio-8009"]

    Oct 12, 2015 9:10:58 AM org.apache.catalina.startup.Catalina start

    INFO: Server startup in 4790 ms

    • websystique

      Hi Anuj,

      You have a ClassNotFoundException. Could you please double check if you are providing the paths properly

      – While creating sessionFactory, Are you providing the proper packages to scan ? sessionFactory.setPackagesToScan(new String[] { “com.websystique.springmvc.model” });?

      - Also, did you annotate your Dao Impl class with @Repository?

      -Finally, is you HibernateCondiguration class is annotated properly?
      @ComponentScan({ “com.websystique.springmvc.configuration” })

      Please check these points, and make sure that the refer to your paths[i can see you ahve different package names than this example]. Let me know if you remain stuck.

  • Arjun Kushwah

    Hi ,

    I am Arjun , I am tring similar to above example but i’m not getting output showing 404 eror

    Oct 6, 2015 1:27:08 PM org.springframework.web.servlet.PageNotFound noHandlerFound

    WARNING: No mapping found for HTTP request with URI [/employee/list] in DispatcherServlet with name ‘dispatcher’.

    Can you help me out.

    • websystique

      Hey Arjun,

      Probably you missed to annotate AppController [ with @Controller]. OR you missed annotating AppConfig [with @ComponentScan(basePackages = "com.websystique.springmvc")].

      Could you please check?

  • Pingback: Quora()

  • RAJ GOPAL

    Can someone please help me i’m not able to get what is the error as i’m new to Spring, Hibernate?

    HTTP Status 500 – Request processing failed; nested exception is
    org.hibernate.MappingException: Unknown entity:
    com.raj.spring.model.Employee

    type Exception report

    message Request processing failed; nested exception is org.hibernate.MappingException: Unknown entity: com.raj.spring.model.Employee

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

    exception

    org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.hibernate.MappingException: Unknown entity: com.raj.spring.model.Employee
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:982)
    org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
    org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)

    root cause

    org.hibernate.MappingException: Unknown entity: com.raj.spring.model.Employee
    org.hibernate.internal.SessionFactoryImpl.getEntityPersister(SessionFactoryImpl.java:1096)
    org.hibernate.internal.SessionImpl.getEntityPersister(SessionImpl.java:1452)
    org.hibernate.engine.internal.ForeignKeys.isTransient(ForeignKeys.java:242)
    org.hibernate.event.internal.AbstractSaveEventListener.getEntityState(AbstractSaveEventListener.java:511)
    org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:116)
    org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:75)
    org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:811)
    org.hibernate.internal.SessionImpl.persist(SessionImpl.java:784)
    org.hibernate.internal.SessionImpl.persist(SessionImpl.java:789)
    com.raj.spring.dao.AbstractDao.persist(AbstractDao.java:35)
    com.raj.spring.dao.EmployeeDaoImpl.saveEmployee(EmployeeDaoImpl.java:21)
    com.raj.spring.service.EmployeeServiceImpl.saveEmployee(EmployeeServiceImpl.java:25)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    java.lang.reflect.Method.invoke(Method.java:497)
    org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:302)
    org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
    org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
    org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
    org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:281)
    org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
    org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
    com.sun.proxy.$Proxy30.saveEmployee(Unknown Source)
    com.raj.spring.controller.AppController.saveEmployee(AppController.java:82)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    java.lang.reflect.Method.invoke(Method.java:497)
    org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
    org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)
    org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:111)
    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:806)
    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:729)
    org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
    org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
    org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
    org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
    org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)

    • websystique

      Hi Raj,

      Did you annotate your Entity [com.raj.spring.model.Employee] with @Entity annotation? Do not also forget to provide the packages to be scanned during SessionFactory setup [in HibernateConfiguration :sessionFactory].

      • RAJ GOPAL

        Yes i did annotate [com.raj.spring.model.Employee].
        Can you help me with which package should i use for SessionFactory setup?

        • websystique

          Hi Raj, I see that you are using the class name where package is required. You need to provide package name [com.raj.spring.model]. Can you change and try again?

          • RAJ GOPAL

            Thank YOu i had already got the error it was the same what you are saying and it works fine now thnks a lot. don’t mind if i ping again :)

        • RAJ GOPAL

          I got what mistake i was making actually i was precisely defing the path upto the Employee bean but i had to give only the package path upto model.
          Thank You @websystique:disqus it really helped me a lot i’ll ping you if i have any further query. Thanks in advance.

  • RAJ GOPAL

    Hello friends,
    I’m facing these issues cans omebody help me as i’m new to spring.

    HTTP Status 500 – Servlet.init() for servlet dispatcher threw exception

    type Exception report

    message Servlet.init() for servlet 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 dispatcher threw exception
    org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
    org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:617)
    org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
    org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)
    org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:668)
    org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1527)
    org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1484)
    java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    java.lang.Thread.run(Thread.java:745)

    root cause

    org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: @Bean method ‘hibernateProperties’ must not be private or final; change the method’s modifiers to continue
    Offending resource: class path resource [com/raj/spring/configuration/HibernateConfiguration.class]
    org.springframework.beans.factory.parsing.FailFastProblemReporter.error(FailFastProblemReporter.java:70)
    org.springframework.context.annotation.BeanMethod.validate(BeanMethod.java:50)
    org.springframework.context.annotation.ConfigurationClass.validate(ConfigurationClass.java:219)
    org.springframework.context.annotation.ConfigurationClassParser.validate(ConfigurationClassParser.java:557)
    org.springframework.context.annotation.ConfigurationClassPostProcessor.processConfigBeanDefinitions(ConfigurationClassPostProcessor.java:322)
    org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry(ConfigurationClassPostProcessor.java:243)
    org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanDefinitionRegistryPostProcessors(PostProcessorRegistrationDelegate.java:273)
    org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:98)
    org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:673)
    org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:519)
    org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:667)
    org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:539)
    org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:493)
    org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
    javax.servlet.GenericServlet.init(GenericServlet.java:158)
    org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
    org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:617)
    org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
    org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)
    org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:668)
    org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1527)
    org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1484)
    java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    java.lang.Thread.run(Thread.java:745)

  • http://junjunguo.com/ guojunjun

    Hi, @websystique:disqus thanks for the great tutorial !
    Every thing works fine, but when I set “5.0.2.Final” instead of “4.3.6.Final”
    I got error message “org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘appController’ … ”

    how do I fix this?

    • websystique

      Hi Guojunjun , Could you paste complete exception here please.That will help me find the real issue.

    • websystique

      Hi Guojunjun,

      Just saw your message with exceptions. I did not try this example with Hibernate 5. From internet sources, It seems there is a compatibility issue with jadira and Hibernate 5. Look at this and this stackoverflow link.

      @Type(type=”org.jadira.usertype.dateandtime.joda.PersistentLocalDate”)
      private LocalDate joiningDate;

      I would need some time to investigate further and find a solution.Till then, i suggest you to stick with hibernate 4.You may also try to remove jadira dependency [by replacing LocalDate with Java.util.Date e.g] and try again.

      • http://junjunguo.com/ guojunjun

        Dear websystique,

        Thank you very much for your time, kind reply with detailed reasoning about my problem, I’m new to Spring and Hibernate did not know where to start debugging.

        I changed Date type to java.sql.Date & java.util.Date (both not working for Hibernate 5, but both working with hibernate 4), I will use hibernate 4 for now, and will try to find a solution for 5 :)

        again Thank you very much for your help!

        here is the exceptions from java.util.Date incase you like to see :)

        HTTP Status 500 – Request processing failed; nested exception is org.springframework.transaction.CannotCreateTransactionException: Could not open Hibernate Session for transaction; nested exception is java.lang.NoClassDefFoundError: org/hibernate/engine/transaction/spi/TransactionContext

        type Exception report

        message Request processing failed; nested exception is org.springframework.transaction.CannotCreateTransactionException: Could not open Hibernate Session for transaction; nested exception is java.lang.NoClassDefFoundError: org/hibernate/engine/transaction/spi/TransactionContext

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

        exception

        org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.transaction.CannotCreateTransactionException: Could not open Hibernate Session for transaction; nested exception is java.lang.NoClassDefFoundError: org/hibernate/engine/transaction/spi/TransactionContext
        org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:982)
        org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
        javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
        org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
        javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
        org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)

  • Erwin

    Hi again. Can you explain what exactly this method does in the AbstractDao class?

    @SuppressWarnings(“unchecked”)
    public AbstractDao(){
    this.persistentClass =(Class) ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[1];
    }

    Is it simply to change the data type of persistentClass to whatever type of data the DAO is persisting into the database?

    • websystique

      Hi Erwin,
      That’s right. With this design, we get flexibility to write generic methods for all entities.

  • Ajay Kumar Yadav

    Hi please help me i am getting below error

    HTTP Status 500 – Servlet.init() for servlet dispatcher threw exception

    type Exception report

    message Servlet.init() for servlet 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 dispatcher threw exception
    org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)
    org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
    org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:957)
    org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:423)
    org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1079)
    org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:620)
    org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
    java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    java.lang.Thread.run(Thread.java:745)

    root cause

    org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘appController’: Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.websystique.springmvc.service.EmployeeService com.websystique.springmvc.controller.AppController.service; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘employeeService’: Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.websystique.springmvc.dao.EmployeeDao com.websystique.springmvc.service.EmployeeServiceImpl.dao; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘employeeDao’: Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.hibernate.SessionFactory com.websystique.springmvc.dao.AbstractDao.sessionFactory; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘sessionFactory’ defined in class path resource [com/websystique/springmvc/configuration/HibernateConfiguration.class]: Invocation of init method failed; nested exception is java.lang.NoSuchFieldError: TRACE
    org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:292)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1185)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
    org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302)
    org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
    org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298)
    org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
    org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:703)
    org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:760)
    org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
    org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:658)
    org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:530)
    org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:484)
    org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)

    • websystique

      Hi Deepak,

      Seems you got the error mentioed in this link. Could you please add slf4j-api & slf4j-log4j12 dependency (latest version) in your pom.xml and try again?

  • Erwin

    Forgive my ignorance, but I read somewhere that you should only use GET methods to retrieve data and not for changing it, since a webcrawler would activate all your delete links should it get onto your page. Is that not an issue here with your deleteEmployee method in the AppController?

    • websystique

      Hi Erwin,

      First of all, you are totally right about it. This example however was more to get us started with a realistic project to work upon, and learn the basics. Now, to be more precise, for a production level application, we should actually use the accurate verbs for each possible action [more of a REST approach]. This Post explains it in great detail. Additionally, notice that we did not even use any security in this application (to keep it short and simple to understand) but in real world app, security is not optional. Spring Security Tutorial goes deep into this aspect. We can even secure application at method level (look at this post) for the same.

      Thanks for sharing your views, i really appreciate it.

      • Erwin

        Thanks for the links, I’m working through those tutorials as we speak :)

  • Aline Santos

    Hi @websystique:disqus ! Thanks again for one more excellent tutorial =)
    I’m having trouble with the listing. When I insert employees, they are correctly saved in database, but the list don’t show them (image attached). Could you give me a clue of what’s happening, please? Thanks in advance.

    • websystique

      Hi Aline, In your case, seems that expressions are not evaluated. Could you please try putting on top part of your jsp’s and try again? Recently one of reader also faced similar issue.

      • Aline Santos

        Yes, it worked! Thanks, @websystique:disqus! Your tutorials are amazing!

        • websystique

          Glad it was helpful.

          • Arjun Kushwah

            Alin You can add it will work 100%

  • badr benabbou

    Hello WebSystique , please i have this error message , i need a help thanks u

    • websystique

      Hey Badr,

      As i asked you in another post as well, Can you let me know the Spring version and server you are using? Do you have spring-webmvc dependency in your pom.xml, as in this post?

      • badr benabbou

        Hey websystique , i found the solution . i had added
        in my jsp file . thanks you for this post . it have been interested .

  • Dixy Xavier

    Hi websystique, I am a newbie to spring MVC and hibernate. This tutorial is pretty awesome. But I found a problem when I imported this as maven project. When I run it in tomcat server it gives HTTP status 404. My IDE is eclipse luna and I use tomcat server version 8.0. It would be great if you could you help me out. Thanks in advance :)
    And sorry for the comments deleted. Was not able to load the image

    • websystique

      Hi Dixy,

      Ok i get it. The problem is not with project but with your tomcat configuration, You seems to be using tomcat plugin on eclipse to deploy it.

      You may then want to look at This,this & this.

      In case you still struggle to setup tomcat working with eclipse properly, you can do following [old school] instead:

      - Install tomcat on your local file system [ I suppose you already have]
      - Build the project on command line[ mvn clean install , means you need to install maven on your machine] or via m2eclipse plugin[from within eclipse].
      - Then copy the war into tomcat/webapps folder manually. restart tomcat [from tomcat/bin/startup.bat], et voila.

    • websystique

      Hi Dixy,
      I’ve just created a post about How To setup tomcat with Eclipse using one of the project. Every step is shown in detail. In case you are still struggling with making tomcat and eclipse work together, the post will surely help you.

      • Dixy Xavier

        Thank you websystique. I always get confused with these setup steps. This link helps me out. Once again thank you for this detailed description with screenshots.

  • Dixy Xavier

    hi websystique, I am a newbie to spring MVC and hibernate. This tutorial is pretty awesome. But I found a problem when I imported this as maven project. When I run it in tomcat server it gives HTTP status 404. My IDE is eclipse luna and I use tomcat server version 8.0. It would be great if you could you help me out. Thanks in advance :)

  • Dixy Xavier

    hi websystique, I am a newbie to spring MVC and hibernate. This tutorial is pretty awesome. But I found a problem when I imported this as maven project. When I run it in tomcat server it gives HTTP status 404. My IDE is eclipse luna and I use tomcat server version 8.0. Could you help me out. Thanks in advance :)

  • Dixy Xavier

    hi websystique, I am a newbie to spring MVC and hibernate. This tutorial is pretty awesome. But I found a problem when I imported this as maven project. When I run it in tomcat server it gives HTTP status 404. My IDE is eclipse luna and I use tomcat server version 8.0. Could you help me out.

  • Dixy Xavier

    hi websystique, I am a newbie to spring MVC and hibernate. This tutorial is pretty awesome. But I found a problem when I imported this as maven project. When I run it in tomcat server it gives HTTP status 404. My IDE is eclipse luna and I use tomcat server version 8.0. Could you help me out

  • Pingback: Spring Framework Project not loading? | Wikiask.info()

  • Pingback: Spring Framework Project not loading? - BlogoSfera()

  • Benny Wur

    Hi, I created another folder under WEB-INF called style and place custom css files which are called by jsp files however when I run the application those css files can not be reached.

    The warning : WARNING: No mapping found for HTTP request with URI [/EKSI-MAC/public/css/navbar-theme.css] in DispatcherServlet with name ‘dispatcher’.

    So, how can add mappings to dispatcher so that I can reach customer css or js files? Thanks!

    • websystique

      Hey Benny, Glad to see you again.

      Look at This Post to do the same.

      Basically, you can extend your spring configuration class from WebMvcConfigurerAdapter and then override addResourceHandlers as shown below.

      @Configuration
      @EnableWebMvc
      @ComponentScan(basePackages = “com.websystique.springmvc”)
      public class AppConfig extends WebMvcConfigurerAdapter{

      ……

      @Override
      public void addResourceHandlers(ResourceHandlerRegistry registry) {
      registry.addResourceHandler(“/static/**”).addResourceLocations(“/static/”);
      }

      ……….
      }

      In above example, i used /static/ in URL’s and placed my files in static folder. You can use ‘style’ instead of static (although i would have preferred static over style).

      • Benny Wur

        That works perfectly, Perhaps I should search more in the blog then come up with questions :) Thanks a lot!

  • Benny Wur

    Thanks a lot! I created the project on my local (import from existing maven projects) and command Maven-Install. it builds fine. However when I run on Tomcat in eclipse I got that error

    HTTP Status 404 – /SpringHibernateExample/

    type Status report

    message /SpringHibernateExample/

    description The requested resource is not available.

    Tomcat starts but can’t find the application?

    • Benny Wur

      Problem resolved. I created the project from beginning and copied all the files. Thanks a lot. Hope you will add more tutorials also would be great it you make videos about them.

      • websystique

        Hey Benny, thanks for visiting this blog. Yes i am actively putting new tutorials.Check the interesting posts links on top of this post, you might find them useful. And thanks for suggesting about videos, may be in near future i will start on them.

        • Benny Wur

          Great to hear. This blog is really helpful.

  • http://timposu.com Ucup Timposu

    Bookmark this site!!!!

    • websystique

      Glad you like it.

  • Pingback: Spring 4 MVC ContentNegotiatingViewResolver example - WebSystique()

  • Pingback: Spring 4 + Hibernate 4 + MySQL+ Maven Integration example (Annotations+XML) - WebSystique()

  • Pingback: How to setup MySQL on local PC - WebSystique()

  • Pingback: Spring 4 MVC+Hibernate 4+MySQL+Maven integration + Testing example using annotations - WebSystique()

  • sachin dhiman

    Hi I am not using MAVEN for adding jar file. I followed the step. I added war file in Tomcat server. but its not loading my application. could you please tell me how can I load application in tomcat if i am not using maven.

    • websystique

      Hey Sachin, even if you are using any other tools(ant/gradle/…), they will provide ways to generate war/ear for you web application. Just make sure all dependencies are included with war. You need to deploy that war into any Servlet 3.0 container(Tomcat 7/8 e.g.). For tomcat, you simply need to put war into webapps folder and then start server [ click on start.bat in tomcat/bin].

      Feel free to ask if you face any other issue.

  • Максим Микрюков

    Thank you very much! your website saved me. but you need to mention one very important thing that is not obvious to newcomers to Java, such as I am! It is necessary to create a Maven project from scratch, without the project templates, otherwise there will be problems

    • websystique

      Hi Maxim,I agree. But you can create a maven project from template(maven-archetype-webapp) as well, create required java/,test/ folder manually in eclipse [ & refresh after adding folders]. It works without issue.Checkout maven posts on this blog for further help.

  • Максим Микрюков

    After .net lacks LINQ

  • Bokor Yan

    Thanks for you great tutorial, but I follow your tutorial and I got a problem, the logging in my console said that the “Could not instantiate bean class [org.hibernate.SessionFactory]: Specified class is an interface”, and the truth is that I found SessionFactory is an interface indeed, so I got nowhere to go?Can you help me fix it?

    • websystique

      Hey Yan,

      Be sure to include Configuration class [HibernateConfiguration annotated with @Configuration as defined above]. This class have bunch of @Bean methods. One of them is sessionFactory(), which returns hibernate LocalSessionFactoryBean class which indeed provides an implementation for SessionFactory interface you are looking for. I hope it’s clear to you now. Feel free to discuss if you have any other question.

      • Bokor Yan

        Thanks for you quick response, :) but I’ve checked my HibernateConfiguration in package com.bitbook.configuration that it is indeed annotated with @configuration and included a method named LocalSessionFactoryBean() that return a SessionFactory implementation, and it is annotated with @Bean, so I sure the SessionFactory bean should be created correctly, so what is the problem then?

        • websystique

          Could you please make sure you are using the same jar versions mentioned in pom.xml of this post? Do you see any difference in jar versions with this post and your project?

      • Bokor Yan

        //that’s my HibernateConfiguration class
        package com.bitbook.configuration;

        //imports

        @Configuration

        @EnableTransactionManagement

        @ComponentScan({ “com.bitbook.configuration” })

        @PropertySource(value = { “classpath:application.properties” })

        public class HibernateConfiguration {

        @Autowired

        private Environment environment;

        @Bean

        public LocalSessionFactoryBean sessionFactory() {

        LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();

        sessionFactory.setDataSource(dataSource());

        sessionFactory.setPackagesToScan(new String[] { “com.bitbook.model” });

        sessionFactory.setHibernateProperties(hibernateProperties());

        return sessionFactory;

        }

        @Bean

        public DataSource dataSource() {

        DriverManagerDataSource dataSource = new DriverManagerDataSource();

        dataSource.setDriverClassName(environment.getRequiredProperty(“jdbc.driverClassName”));

        dataSource.setUrl(environment.getRequiredProperty(“jdbc.url”));

        dataSource.setUsername(environment.getRequiredProperty(“jdbc.username”));

        dataSource.setPassword(environment.getRequiredProperty(“jdbc.password”));

        return dataSource;

        }

        private Properties hibernateProperties() {

        Properties properties = new Properties();

        properties.put(“hibernate.dialect”, environment.getRequiredProperty(“hibernate.dialect”));

        properties.put(“hibernate.show_sql”, environment.getRequiredProperty(“hibernate.show_sql”));

        properties.put(“hibernate.format_sql”, environment.getRequiredProperty(“hibernate.format_sql”));

        return properties;

        }

        @Bean

        @Autowired

        public HibernateTransactionManager transactionManager(SessionFactory s) {

        HibernateTransactionManager txManager = new HibernateTransactionManager();

        txManager.setSessionFactory(s);

        return txManager;

        }

        }

  • Declan Nishiyama

    This tutorial is great! I really appreciate it as I’m struggling to get persistent data storage in a servlet. The only problem I’m still having is with the MySQL portion of the tutorial. You mention to “Create schema in database” in step 11, but where does this data go? Also, do I need to initialize something to have the “jdbc:mysql://localhost:3306/websystique” function correctly? I tried to look at the MySQL manual, but it is very dense and I’m not even sure where to begin. Thank you for whatever help you can provide!

    • websystique

      Hey Declan,

      Sorry for late reply. Yes you first need to setup your MySQL database. I agree that i should have discussed about it but i missed it. Anyway, simplest way to install MySQL is through installing MySQL workbench [https://www.mysql.com/products/workbench/] downloadable at [http://dev.mysql.com/downloads/workbench/] which provides a simple GUI to create and manage database, and execute sql. I too used the workbench for this post.

      Workbench GUI provides easy way to create a mysql database. Just give a name to db, and the default URL to be used to connect to your brand new DB will be jdbc:mysql://localhost:3306/yourDB. Port 3306 is the default port, but you can change it if you want.

      • Declan Nishiyama

        Thanks! This is exactly what I was needing. I really appreciate it

  • Daniel Mota

    I’m trying to use two model in a form on my JSP. For example Question and Answers.

    public class Answer {
    private String text;
    Getter and Setter...
    }

    public class Question {
    private String text;
    Getter and Setter...
    }

    public class QuestionForm {
    private Question = new Question();
    private ArrayList answers = new ArrayList();
    Getter and Setter...
    }

    I’m using QuestionForm as model on my JSP. So only messages set for QuestionForm are shown as ERRO. Stil that I set : @NotNull @NotEmpty @Size and another in Question and Answer.

    How catch several modelAttribute on my Controller class?

    • Daniel Mota

      SOLVED!

  • Shekhar

    I got contextInitialization failed. Detail error is:

    Jun 6, 2015 11:16:19 AM EDT> <Context initialization failed

    Error creating bean with name 'appController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.websystique.springmvc.service.EmployeeService com.websystique.springmvc.controller.AppController.service; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'employeeService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.websystique.springmvc.dao.EmployeeDao com.websystique.springmvc.service.EmployeeServiceImpl.dao; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'employeeDao': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.hibernate.SessionFactory com.websystique.springmvc.dao.AbstractDao.sessionFactory; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in class path resource [com/websystique/springmvc/configuration/HibernateConfiguration.class]: Invocation of init method failed; nested exception is java.lang.NoSuchMethodError: javax.persistence.Table.indexes()[Ljavax/persistence/Index;

    • websystique

      Are you somehow also including JPA 2.0 API in your project? Reason for this error [nosuchmethoderror : javax.persistence.table.indexes()] is defined in JPA 2.1 API which are implemented by Hibernate version 4.3.X (as in our example).So there seems multiple version of JPA included in your project. Exclude JPA 2.0 API in your pom.xml or declare JPA 2.1 API version explicitly in your pom.xml to force project to use 2.1 version.

      • Shekhar

        No I was not using that. Looks like Weblogic 12c does not support JPA 2.1. So, I used hibernate 4.1.9 that supports JPA 2.0. Now it is working fine. But not sure how can I adjust Hibernate 4.3.6, JPA 2.1 and Weblogic 12C

  • SB

    When I am executing mvn clean install command m getting compilation errors as below:-

    [ERROR] MoneyLendingSpringHibernateExamplesrcmainjavacomwebsystiquesprin

    gmvcconfigurationAppConfig.java:[4,1] cannot find symbol

    symbol: class Configuration

    @Configuration

    [ERROR] MoneyLendingSpringHibernateExamplesrcmainjavacomwebsystiquesprin

    gmvcconfigurationAppConfig.java:[5,1] cannot find symbol

    symbol: class EnableWebMvc

    @EnableWebMvc

    [ERROR] MoneyLendingSpringHibernateExamplesrcmainjavacomwebsystiquesprin

    gmvcconfigurationAppConfig.java:[6,1] cannot find symbol

    symbol: class ComponentScan

    @ComponentScan(basePackages = “com.websystique.springmvc”)

    [ERROR] MoneyLendingSpringHibernateExamplesrcmainjavacomwebsystiquesprin

    gmvcconfigurationAppConfig.java:[10,8] cannot find symbol

    symbol : class ViewResolver

    location: class com.websystique.springmvc.configuration.AppConfig

    [ERROR] MoneyLendingSpringHibernateExamplesrcmainjavacomwebsystiquesprin

    gmvcconfigurationAppConfig.java:[20,8] cannot find symbol

    symbol : class MessageSource

    location: class com.websystique.springmvc.configuration.AppConfig

    [ERROR] MoneyLendingSpringHibernateExamplesrcmainjavacomwebsystiquesprin

    gmvcconfigurationAppConfig.java:[9,2] cannot find symbol

    symbol : class Bean

    Please let us know the issue.

    • websystique

      Hi SB,

      Please make sure that you have spring dependency declared in your pom.xml. All errors you mentioned above seems due to missing spring dependency.

  • Klaas van G.

    Interesting tutorial, as I am pretty new with Spring and Hibernate and was desperately looking for a tutorial which combines Spring, Hibernate and Maven in a demo project which I can modify and extend.

    I have not run the tutorial yet and am a bit confused about the following:

    The form does not define an action attribute, so how does it know which controller method must be executed after submit? It only defines: modelAttribute=”employee”

    But how does this map to the saveEmployee(…) method of the Controller which is mapped by the /new URL in the RequestMapping annotation? Obvious I am missing something…

    • websystique

      Hi, It is all with Url & HTTP methods mapping inside controller. Let me explain.
      1) When you simply go to URL http://localhost:8080/SpringHibernateExample/ [first step], You are asking to controller to look for a method which can handle URL “/” with HTTP GET.

      In this case, listEmployees will be called because it is annotated with @RequestMapping(value = { “/”, “/list” }, method = RequestMethod.GET). Perfect match.

      2) When you click on “Add New Employee” link [second step], URL asked for is “/new” , again a HTTP get, so newEmployee method will be invoked.

      3) When you click on “Register” [third step], URL asked for is still “/new” , but it’s an HTTP Post this time (form submission), so saveEmployee method will be invoked.

      Hope it helps. I strongly suggest you to refer to initial Spring tutorial as well in this site, to get basic concepts cleared. Any doubt, feel free to ask.

  • Daniel Mota

    Hi,
    I’m newbie on world Java Spring.
    Can you indicate a book for I learn as develop with the techniques showed here?

    • websystique

      Hi Daniel,
      It may be hard to find a book which goes mainly on complete integration as shown here.Though you may find one or two simple examples in any framework book.

      For spring newbies, my suggestion would be : Spring in action latest edition (Manning)

      For hibernate : Java persistence with Hibernate (Manning).
      For MySQL : go over manual, they are the best source available.

      And rest, feel free to ask question, that’s how we learn.

      • Daniel Mota

        Thank you for all suggestions…
        I’ll begin read about spring…
        When appear new question, I come back here.

  • Manjunath M

    hi i have imported the source code by downloading ,, i am getting an error as below image ,,

    i am copying it to linux fedora ..is it fine ???

    • websystique

      Yes it will be fine.You should upgrade to higher jdk version. There is no error as such with project. The one you see are under javascript tab(i don;t have any javascript in this project). It can be ignored.

  • Breno Costa

    Hi, congratulations for this awesome tutorial!
    I have one question. There are many web frameworks and languages, and this generate some confusion in the choosing. I’ve read blogs saying jsp – and jsf too – is dead (old, legacy).
    What do you think about it? JSP is used in many applications with spring mvc? IS there an other alternatives?

    • websystique

      There are few quick choices(solely based on my experience, although several other options are out there)

      – Use latest angularJs on FE [through plain velocity templates e.g.] using spring mvc. You get the latest and greatest FE technology while still sitting under spring mvc umbrella.

      - Willing to dump spring mvc altogether, Use Wicket. It’s awesome if you are willing to learn, it could be complex in the beginning but once you get the hands on it, your imagination is the only limit.

      - Use pure javascript solutions (AngularJS on FE and NodeJS on BE).

      Feel free to share your thoughts, i like this kind of discussion.

  • Pingback: Spring Tutorial | k1025989's e-Portfolio()

  • Jonathan Willis

    Are you planning on adding testing configuration for this tutorial?

    • websystique

      Dear Jonathan, thanks for reminding me. Yes i am going to find sometime soon add test coverage with necessary configuration.

    • websystique

      Hey Jonathan,

      Post has been adapted with more functionality and a new Test post has been added with TestNG, Mockito, DBUnit & Spring-test.

  • Andy

    Very good tutorial and thank you for sharing.

  • Puneeth Shivalingaiah

    Excellent :)

  • Javier Lucena

    Hi, I tried run this example but I had the error 404: The requested resource is not available. And the last line in IDE console was:

    feb 18, 2015 12:29:36 AM org.apache.catalina.startup.Catalina start
    INFO: Server startup in 658 ms

    Could you help me? Thank you.

  • Joe

    Your tutorial works great. I am happy to see my Spring MVC app working great for the first time courtesy of your tutorial that I saw online. Everything works great without xml. Thank you very much

  • Plerisei

    Thanks for the tutorial. Trying to work this out, hopefully I get it up and running. I haven’t added views yet, as I want to use .html and angular. I have all the files setup just before the views section. Anyway for me to run the app (without the views) and verify I’m pulling data from the database with the Get call? Thanks.

    • websystique

      Hi Plerisei,
      You can write unit test for the service layer and data layer.That’s how usually we validate our individual layer without views.

      Hope it helps,let me know if you need some help for the testing part(i would be adding a separate post on testing soon…)

      Regards
      WebSystique Admin

      • jack

        please add more testing part. Thanks

        • websystique

          Hey Jack,

          Post has been adapted with more functionality and a new Test post has been added with TestNG, Mockito, DBUnit & Spring-test.

          Let me know your feedback.

  • John

    I just registered to say that this tutorial is pretty good. I have some experience with spring mvc and hibernate and i can say that this is really good compared to most other tutorials on web. Great!

    • websystiqueadmin

      Thanks John,

      I really appreciate your feedback. This blog is still young and we are trying our best to improve it as far as we can which will surely require feedback from supportive users like you.

      Thanks again,
      WebSystique Admin

    • websystique

      Thanks, I appreciate your feedback. Please visit other posts on this blog and provide us your valuable comments.