Spring 4 + Hibernate 4 + MySQL+ Maven Integration example (Annotations+XML)

In this tutorial , we will integrate Spring 4 with Hibernate 4 using annotation based configuration. We will develop a simple CRUD java application , creating hibernate entities, saving data in MySQL database , performing database CRUD operations within transaction, and learn how different layers interacts with each-other in typical enterprise application, all using annotation based configuration. We will also see corresponding XML configuration side-by-side for comparison.

For Spring MVC based application, checkout Spring4 MVC Hibernate and MySQL integration.


Following technologies being used:

  • Spring 4.0.6.RELEASE
  • Hibernate Core 4.3.6.Final
  • MySQL Server 5.6
  • Joda-time 2.3
  • Maven 3
  • JDK 1.6
  • Eclipse JUNO Service Release 2

Project directory structure

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

Step 1: Update pom.xml to include required dependencies

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

	<modelVersion>4.0.0</modelVersion>
	<groupId>com.websystique.spring</groupId>
	<artifactId>Spring4HibernateExample</artifactId>
	<version>1.0.0</version>
	<packaging>jar</packaging>

	<name>Spring4HibernateExample</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>
	</properties>

	<dependencies>

		<!-- Spring -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${springframework.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</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>

		<!-- 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>

	</dependencies>
	<build>
		<pluginManagement>
			<plugins>
				<plugin>
					<groupId>org.apache.maven.plugins</groupId>
					<artifactId>maven-compiler-plugin</artifactId>
					<version>3.2</version>
					<configuration>
						<source>1.6</source>
						<target>1.6</target>
					</configuration>
				</plugin>
			</plugins>
		</pluginManagement>
	</build>

</project>

Spring, Hibernate & MySQL connector dependencies are pretty obvious. We have also included joda-time as we will use joda-time library for any date manipulation. usertype-core is included to provide the mapping between database date-type and joda-time LocalDate.

Step 2: Configure Hibernate

com.websystique.spring.configuration.HibernateConfiguration

package com.websystique.spring.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.spring.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.spring.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.

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 = false
hibernate.format_sql = false

Corresponding XML based Hibernate configuration

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:context="http://www.springframework.org/schema/context"
        xmlns:tx="http://www.springframework.org/schema/tx"
        xmlns:aop="http://www.springframework.org/schema/aop"
        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        					http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
        					http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
        					http://www.springframework.org/schema/tx  http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">

	
	<context:property-placeholder location="classpath:application.properties" />
	
	<context:component-scan  base-package="com.websystique.spring" />
	
	<tx:annotation-driven transaction-manager="transactionManager"/>
	
	<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="driverClassName" value="${jdbc.driverClassName}" />
		<property name="url" value="${jdbc.url}"/>
		<property name="username" value="${jdbc.username}" />
		<property name="password" value="${jdbc.password}"/>
		
  	</bean>
	
	<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" >
		<property name="dataSource" ref="dataSource"/>
		<property name="packagesToScan">
			<list>
				<value>com.websystique.spring.model</value>
			</list>
		</property>
		<property name="hibernateProperties">
			<props>
 				<prop key="hibernate.dialect">${hibernate.dialect}</prop>
				<prop key="hibernate.show_sql">${hibernate.show_sql:false}</prop>
				<prop key="hibernate.format_sql">${hibernate.format_sql:false}</prop>
			</props>
		</property>		
	</bean>

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

	<bean id="persistenceExceptionTranslationPostProcessor"
    	class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>
    	
</beans>

Step 3: Configure Spring

com.websystique.spring.configuration.AppConfig

package com.websystique.spring.configuration;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan(basePackages = "com.websystique.spring")
public class AppConfig {

}

In our simple example, this class is empty and only reason for it’s existence is @ComponentScan which provides beans auto-detection facility. You may completely remove above configuration and put the component scan logic in application context level (in Main ). In full-fledged applications, you may find it handy to configure some beans (e.g. messageSource, PropertySourcesPlaceHolderConfigurer) in Configuration class.

Corresponding XML based Spring Configuration

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
	http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
 
	<context:component-scan base-package="com.websystique.spring" />
 
</beans>

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, Domain object, sample database schema and run the application.

Step 4: Add DAO Layer

com.websystique.spring.dao.AbstractDao

package com.websystique.spring.dao;

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

public abstract class AbstractDao {

	@Autowired
	private SessionFactory sessionFactory;

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

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

	public void delete(Object entity) {
		getSession().delete(entity);
	}
}

Notice above, that SessionFactory we have created earlier in step 2, will be auto-wired here.This class serve as base class for database related operations.

com.websystique.spring.dao.EmployeeDao

package com.websystique.spring.dao;

import java.util.List;

import com.websystique.spring.model.Employee;

public interface EmployeeDao {

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

com.websystique.spring.dao.EmployeeDaoImpl

package com.websystique.spring.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.spring.model.Employee;

@Repository("employeeDao")
public class EmployeeDaoImpl extends AbstractDao implements EmployeeDao{

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

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

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

	
	public Employee findBySsn(String ssn){
		Criteria criteria = getSession().createCriteria(Employee.class);
		criteria.add(Restrictions.eq("ssn",ssn));
		return (Employee) criteria.uniqueResult();
	}
	
	public void updateEmployee(Employee employee){
		getSession().update(employee);
	}
	
}

Step 5: Add Service Layer

com.websystique.spring.service.EmployeeService

package com.websystique.spring.service;

import java.util.List;

import com.websystique.spring.model.Employee;

public interface EmployeeService {

	void saveEmployee(Employee employee);

	List<Employee> findAllEmployees();

	void deleteEmployeeBySsn(String ssn);

	Employee findBySsn(String ssn);

	void updateEmployee(Employee employee);
}

com.websystique.spring.service.EmployeeServiceImpl

package com.websystique.spring.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.spring.dao.EmployeeDao;
import com.websystique.spring.model.Employee;

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

	@Autowired
	private EmployeeDao dao;
	
	public void saveEmployee(Employee employee) {
		dao.saveEmployee(employee);
	}

	public List<Employee> findAllEmployees() {
		return dao.findAllEmployees();
	}

	public void deleteEmployeeBySsn(String ssn) {
		dao.deleteEmployeeBySsn(ssn);
	}

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

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

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 6: Create Domain Entity Class(POJO)

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

com.websystique.spring.model.Employee

package com.websystique.spring.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 org.hibernate.annotations.Type;
import org.joda.time.LocalDate;

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

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

	@Column(name = "NAME", nullable = false)
	private String name;

	@Column(name = "JOINING_DATE", nullable = false)
	@Type(type="org.jadira.usertype.dateandtime.joda.PersistentLocalDate")
	private LocalDate joiningDate;

	@Column(name = "SALARY", nullable = false)
	private BigDecimal salary;
	
	@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

Step 7: 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 8: Create Main to run as Java Application

package com.websystique.spring;

import java.math.BigDecimal;
import java.util.List;

import org.joda.time.LocalDate;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;

import com.websystique.spring.configuration.AppConfig;
import com.websystique.spring.model.Employee;
import com.websystique.spring.service.EmployeeService;

public class AppMain {

	public static void main(String args[]) {
		AbstractApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);

		EmployeeService service = (EmployeeService) context.getBean("employeeService");

		/*
		 * Create Employee1
		 */
		Employee employee1 = new Employee();
		employee1.setName("Han Yenn");
		employee1.setJoiningDate(new LocalDate(2010, 10, 10));
		employee1.setSalary(new BigDecimal(10000));
		employee1.setSsn("ssn00000001");

		/*
		 * Create Employee2
		 */
		Employee employee2 = new Employee();
		employee2.setName("Dan Thomas");
		employee2.setJoiningDate(new LocalDate(2012, 11, 11));
		employee2.setSalary(new BigDecimal(20000));
		employee2.setSsn("ssn00000002");

		/*
		 * Persist both Employees
		 */
		service.saveEmployee(employee1);
		service.saveEmployee(employee2);

		/*
		 * Get all employees list from database
		 */
		List<Employee> employees = service.findAllEmployees();
		for (Employee emp : employees) {
			System.out.println(emp);
		}

		/*
		 * delete an employee
		 */
		service.deleteEmployeeBySsn("ssn00000002");

		/*
		 * update an employee
		 */

		Employee employee = service.findBySsn("ssn00000001");
		employee.setSalary(new BigDecimal(50000));
		service.updateEmployee(employee);

		/*
		 * Get all employees list from database
		 */
		List<Employee> employeeList = service.findAllEmployees();
		for (Employee emp : employeeList) {
			System.out.println(emp);
		}

		context.close();
	}
}

Note : In case you want to drop AppConfig altogether, in above main, you just have to replace

		AbstractApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);

with

		AnnotationConfigApplicationContext  context = new AnnotationConfigApplicationContext();
		context.scan("com.websystique.spring"); 
		context.refresh();

Rest of code remains same. Run above program, you will see following output

Employee [id=1, name=Han Yenn, joiningDate=2010-10-10, salary=10000, ssn=ssn00000001]
Employee [id=2, name=Dan Thomas, joiningDate=2012-11-11, salary=20000, ssn=ssn00000002]
Employee [id=1, name=Han Yenn, joiningDate=2010-10-10, salary=50000, ssn=ssn00000001]

That’s it.

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?

  • MacBooK

    oh My Man, thank you so much!

  • Antonio Andrés Jiménez Navas

    Amazing! Thank you! You made my day!

  • Sébastien Paquet

    Hello,
    thank you for the working example,

    Could you explain how
    from the bean, returning a LocalSessionFactoryBean
    you get the SessionFactory object required in the HibernateConfiguration and the AbstractDao

    @Bean
    @Autowired
    public HibernateTransactionManager transactionManager(SessionFactory s) {

    public abstract class AbstractDao {
    @Autowired
    private SessionFactory sessionFactory;

    Thank you !

    • websystique

      Hi Sebastien, 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.

  • snake pliskin

    Hi!

    I would like to know how can i add the OpenSessionInViewFilter in the spring configuration to avoid use eager in the fetch field.

    Thank you so much.

    • websystique

      Hi, I prefer not to use the OpenSessionInViewFilter/Inteceptor and handle the init issues mysefl. But if you want to use it, would recommend using OpenSessionInViewInterceptor as this can be configured in application-context [in contrast to OpenSessionInViewFilter which needs to be configured in web.xml]. For non-web application, it should be something like:

      public @Bean(name=”openSessionInViewInterceptor”) OpenSessionInViewInterceptor openSessionInViewInterceptor(){
      final OpenSessionInViewInterceptor openSessionInViewInterceptor = new OpenSessionInViewInterceptor();
      openSessionInViewInterceptor.setSessionFactory(this.sessionFactory);
      openSessionInViewInterceptor.setSingleSession(true);
      return openSessionInViewInterceptor;
      }

      For Web application,

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

      ….
      @Override
      public void addInterceptors(InterceptorRegistry registry) {
      OpenSessionInViewInterceptor interceptor = new OpenSessionInViewInterceptor();
      interceptor.setSessionFactory(sessionFactory);
      registry.addInterceptor(interceptor)
      }
      ….
      }

      • snake pliskin

        Thank you so much!! :-)
        I’m going to try it and I will tell you if it works

  • raaj

    Hi

    Would you be okay if I took your source for my project, at the company?

    • websystique

      Hi Raj, Yes you can use it for your internal projects at your company. Glad you find it useful. Best of luck.

  • sujit shelar

    Hey your website very helpful for me, and improve mvc knowledge.
    thanx for helping.

    • websystique

      Hey Sujit, Glad it was helpful.

  • mukesh tangri

    Thanks. Question, why is my dao always null in the serviceImpl class? i made sure the base package path is perfect. in the logs i can see bean is being created for my dao

    2016-03-15 23:20:28,299 DEBUG [org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor] – Autowiring by type from bean name ‘eventDao’ to bean named ‘sessionFactory’
    2016-03-15 23:20:28,300 DEBUG [org.springframework.beans.factory.support.DefaultListableBeanFactory] – Returning cached instance of singleton bean ‘org.springframework.transaction.config.internalTransactionAdvisor’
    2016-03-15 23:20:28,302 DEBUG [org.springframework.beans.factory.support.DefaultListableBeanFactory] – Finished creating instance of bean ‘eventDao’

  • Kumar Panchal

    Perfect Explanation…

    • websystique

      Glad you liked it.

  • Ashay Kolhe

    Perfect.

    Although, hbm2ddl doesn’t seem to create database directly. I had to create the DB manually and then set hbm2ddl to update and then it created the table.

    • websystique

      Hi Ashay, I too have created the database manually. Anyway, This is not the first time i got this comment, so I am going to look into the hbm2ddl issue to see if we can improve this post even further, to handle automatic create-drop. Thanks for reminding me.

  • Ramu

    hi sir i tried to use your code in my project i ma getting this exception please help me

    Exception in thread “main” org.springframework.transaction.CannotCreateTransactionException: Could not open Hibernate Session for transaction; nested exception is org.hibernate.exception.SQLGrammarException: Could not open connection

    at org.springframework.orm.hibernate4.HibernateTransactionManager.doBegin(HibernateTransactionManager.java:515)

    at org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:373)

    at org.springframework.transaction.interceptor.TransactionAspectSupport.createTransactionIfNecessary(TransactionAspectSupport.java:420)

    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:257)

    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95)

    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)

    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)

    at com.sun.proxy.$Proxy26.findAllEmployees(Unknown Source)

    at com.life.webservices.CallWebServices.main(CallWebServices.java:18)

    Caused by: org.hibernate.exception.SQLGrammarException: Could not open connection

    at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:122)

    at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49)

    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:125)

    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:110)

    at org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.obtainConnection(LogicalConnectionImpl.java:304)

    at org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.getConnection(LogicalConnectionImpl.java:169)

    at org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction.doBegin(JdbcTransaction.java:67)

    at org.hibernate.engine.transaction.spi.AbstractTransactionImpl.begin(AbstractTransactionImpl.java:160)

    at org.hibernate.internal.SessionImpl.beginTransaction(SessionImpl.java:1395)

    at org.springframework.orm.hibernate4.HibernateTransactionManager.doBegin(HibernateTransactionManager.java:474)

    … 8 more

    Caused by: com.microsoft.sqlserver.jdbc.SQLServerException: Login failed for user ‘design ‘.

    at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:196)

    at com.microsoft.sqlserver.jdbc.TDSTokenHandler.onEOF(tdsparser.java:246)

    at com.microsoft.sqlserver.jdbc.TDSParser.parse(tdsparser.java:83)

    at com.microsoft.sqlserver.jdbc.SQLServerConnection.sendLogon(SQLServerConnection.java:2532)

    at com.microsoft.sqlserver.jdbc.SQLServerConnection.logon(SQLServerConnection.java:1929)

    at com.microsoft.sqlserver.jdbc.SQLServerConnection.access$000(SQLServerConnection.java:41)

    at com.microsoft.sqlserver.jdbc.SQLServerConnection$LogonCommand.doExecute(SQLServerConnection.java:1917)

    at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:4026)

    at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:1416)

    at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectHelper(SQLServerConnection.java:1061)

    at com.microsoft.sqlserver.jdbc.SQLServerConnection.login(SQLServerConnection.java:833)

    at com.microsoft.sqlserver.jdbc.SQLServerConnection.connect(SQLServerConnection.java:716)

    at com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(SQLServerDriver.java:841)

    at java.sql.DriverManager.getConnection(Unknown Source)

    at java.sql.DriverManager.getConnection(Unknown Source)

    at org.springframework.jdbc.datasource.DriverManagerDataSource.getConnectionFromDriverManager(DriverManagerDataSource.java:153)

    at org.springframework.jdbc.datasource.DriverManagerDataSource.getConnectionFromDriver(DriverManagerDataSource.java:144)

    at org.springframework.jdbc.datasource.AbstractDriverBasedDataSource.getConnectionFromDriver(AbstractDriverBasedDataSource.java:155)

    at org.springframework.jdbc.datasource.AbstractDriverBasedDataSource.getConnection(AbstractDriverBasedDataSource.java:120)

    at org.hibernate.service.jdbc.connections.internal.DatasourceConnectionProviderImpl.getConnection(DatasourceConnectionProviderImpl.java:141)

    at org.hibernate.internal.AbstractSessionImpl$NonContextualJdbcConnectionAccess.obtainConnection(AbstractSessionImpl.java:292)

    at org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.obtainConnection(LogicalConnectionImpl.java:297)

    … 13 more

  • Guilherme Marquesini Reis Ribe

    Hi websys.

    I’m trying to use this code in a old webserver that don’t use Spring MVC, its using @WebServlet of Javax. I just want to include the spring data to manage my transactions instead of I do this mannualy.

    I made all the configurations correctly. I’m trying to call my UserService but I’m getting a NullPointerException when I call a method of this class, like:
    user = userService.createUser(user);

    I believe that the Spring Data didnt starts with my application context. I didnt use the :

    AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
    context.scan(“com.websystique.”);
    context.refresh();

    I need to start this in some place? I think in create a listener on start and run this, but don’t know if its correct way.
    I’m working with web.xml, and added the Java class to configure. Has problem with this?

    • websystique

      Hi Guilherme, Did you try to simply declare contextLoaderListner in web.xml and then provide a seperate XML file [using contextConfigLocation] in which specifying context:component-scan with path to your packages?It should be sufficient.

      • Guilherme Marquesini Reis Ribe

        Hi websys. Thanks for the reply. I solved this without Spring, opening and closing each session on each DAO. Is a old approach of course. I will recommend to migrate to Spring on the next releases.
        Thanks.

  • Luxmanrao Potadar

    hi,
    I am working on your examples. When I created your examples with STS and execute them I am getting error as:Exception in thread “main” org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named “…” but when I download your code and execute it works fine. I am not getting what is causing this issue. Even I tried creating sample maven projects and executed the code I get same error.

    • websystique

      Hi Laxmanrao,

      Could you please post the full exception here, if possible? I want to know which Bean it is complaining about.

  • otuwa

    Hi,

    I followed your tutorial. It was really helpfull. After running it once, i ran the application again. But then error occured saying that duplicate entry and cannot execute. Then I tried adding “hibernate.hbm2ddl.auto=create” and it didn’t work even. Please help me out

    • otuwa

      ERROR: Duplicate entry ‘ssn00000001′ for key ‘ssn’

      Exception in thread “main” org.hibernate.exception.ConstraintViolationException: could not execute statement

      at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:72)

      at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49)

      at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:126)

      at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:112)

      at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:211)

      at org.hibernate.id.IdentityGenerator$GetGeneratedKeysDelegate.executeAndExtract(IdentityGenerator.java:96)

      at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:58)

      at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3032)

      at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3558)

      at org.hibernate.action.internal.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:98)

      at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:490)

      at org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction(ActionQueue.java:195)

      at org.hibernate.engine.spi.ActionQueue.addInsertAction(ActionQueue.java:179)

      at org.hibernate.engine.spi.ActionQueue.addAction(ActionQueue.java:214)

      at org.hibernate.event.internal.AbstractSaveEventListener.addInsertAction(AbstractSaveEventListener.java:324)

      at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:288)

      at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:194)

      at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:125)

      at org.hibernate.event.internal.DefaultPersistEventListener.entityIsTransient(DefaultPersistEventListener.java:206)

      at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:149)

      at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:75)

      at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:811)

      at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:784)

      at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:789)

      at org.otuwa.spring.dao.AbstractDao.persist(AbstractDao.java:17)

      at org.otuwa.spring.dao.EmployeeDaoImpl.saveEmployee(EmployeeDaoImpl.java:15)

      at org.otuwa.spring.service.EmployeeServiceImpl.saveEmployee(EmployeeServiceImpl.java:19)

      at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

      at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)

      at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)

      at java.lang.reflect.Method.invoke(Unknown Source)

      at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)

      at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)

      at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)

      at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:98)

      at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:262)

      at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95)

      at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)

      at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)

      at com.sun.proxy.$Proxy27.saveEmployee(Unknown Source)

      at org.otuwa.spring.AppMain.main(AppMain.java:54)

      Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry ‘ssn00000001′ for key ‘ssn’

      at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)

      at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)

      at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)

      at java.lang.reflect.Constructor.newInstance(Unknown Source)

      at com.mysql.jdbc.Util.handleNewInstance(Util.java:408)

      at com.mysql.jdbc.Util.getInstance(Util.java:383)

      at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1049)

      at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4226)

      at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4158)

      at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2615)

      at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2776)

      at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2840)

      at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2082)

      at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2334)

      at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2262)

      at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2246)

      at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:208)

      … 36 more

      • websystique

        Hey otuwa,

        SSN is unique for each employee. So of course you will get ‘duplicate error’ on running it twice. To overcome your issue

        : You can implement you own way to insure uniqueness in SSN (add UUID for example)

        OR

        : You should be using hibernate.hbm2ddl.auto=create-drop: It will drop the schema at the end of the session.

        Let me know if you face any other problem.

        • otuwa

          Thank you very much for your response. I tried create-drop too. According to the definition of create-drop it should work but it’s not. I would be really glad if you could try it & let me know your results.
          Thank you again..

  • deepak

    my data source look like
    jdbc.driverClassName = oracle.jdbc.driver.OracleDriver
    jdbc.url = jdbc:oracle:thin:@localhost:1521:xe
    jdbc.username = hr
    jdbc.password = hr
    hibernate.dialect = org.hibernate.dialect.Oracle10gDialect
    hibernate.show_sql = false
    hibernate.format_sql = false

    • websystique

      Hey Deepak,
      Where exactly did you put this file? If it is in classpath ( e.g. if you have put it in resources folder) it must be found.

      • deepak

        now i changed dataSource.setUrl(environment.getRequiredProperty(“jdbc.url”));
        it saying java.lang.IllegalStateException: required key [hibernate.show_sql ] not found.
        Instantiation of bean failed-hibernateProperties and sessionFactory.

        • deepak

          Hi,
          If u have a skype id..plz share with me on my mail id.so that i could share my screen and show you what happening.

        • websystique

          Hi Deepak, Do you have more than one properties file in your project? It won’t matter much but where exactly did you placed the properties file? Did you try to run the project as it is from download, to see if you succeed to run it? Which version of Spring are you using? Example is so simple & straight-forward , i don’t see why it won’t work for you.

  • deepak

    looks like spring container is unable to find my property file where i defined my data source

  • deepak

    I wrote my code this way..
    @Configuration
    @EnableTransactionManagement
    @ComponentScan({“com.spring4hibernate.configuration”})
    @PropertySource(value = {“classpath:application.properties”})
    public class HibernateConfiguration {
    ===compiler===
    Aug 17, 2015 3:35:41 PM org.springframework.context.annotation.AnnotationConfigApplicationContext prepareRefresh
    INFO: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@34005e1: startup date [Mon Aug 17 15:35:41 IST 2015]; root of context hierarchy
    Aug 17, 2015 3:35:42 PM org.springframework.jdbc.datasource.DriverManagerDataSource setDriverClassName
    INFO: Loaded JDBC driver: oracle.jdbc.driver.OracleDriver
    Exception in thread “main” org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘orderDao’: Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.hibernate.SessionFactory com.spring4hibernate.dao.AbstractDao.sessionFactory; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘sessionFactory’ defined in class path resource [com/spring4hibernate/configuration/HibernateConfiguration.class]: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.springframework.orm.hibernate4.LocalSessionFactoryBean com.spring4hibernate.configuration.HibernateConfiguration.sessionFactory()] threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘dataSource’ defined in class path resource [com/spring4hibernate/configuration/HibernateConfiguration.class]: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public javax.sql.DataSource com.spring4hibernate.configuration.HibernateConfiguration.dataSource()] threw exception; nested exception is java.lang.IllegalStateException: required key [jdbc:oracle:thin:@localhost:1521:xe] not found
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:292)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1185)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:703)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:760)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
    at org.springframework.context.annotation.AnnotationConfigApplicationContext.(AnnotationConfigApplicationContext.java:84)
    at com.spring4hibernate.dto.TestMain.main(TestMain.java:20)
    Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.hibernate.SessionFactory com.spring4hibernate.dao.AbstractDao.sessionFactory; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘sessionFactory’ defined in class path resource [com/spring4hibernate/configuration/HibernateConfiguration.class]: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.springframework.orm.hibernate4.LocalSessionFactoryBean com.spring4hibernate.configuration.HibernateConfiguration.sessionFactory()] threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘dataSource’ defined in class path resource [com/spring4hibernate/configuration/HibernateConfiguration.class]: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public javax.sql.DataSource com.spring4hibernate.configuration.HibernateConfiguration.dataSource()] threw exception; nested exception is java.lang.IllegalStateException: required key [jdbc:oracle:thin:@localhost:1521:xe] not found
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:508)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:289)
    … 12 more
    Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘sessionFactory’ defined in class path resource [com/spring4hibernate/configuration/HibernateConfiguration.class]: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.springframework.orm.hibernate4.LocalSessionFactoryBean com.spring4hibernate.configuration.HibernateConfiguration.sessionFactory()] threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘dataSource’ defined in class path resource [com/spring4hibernate/configuration/HibernateConfiguration.class]: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public javax.sql.DataSource com.spring4hibernate.configuration.HibernateConfiguration.dataSource()] threw exception; nested exception is java.lang.IllegalStateException: required key [jdbc:oracle:thin:@localhost:1521:xe] not found
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:597)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1094)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:989)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:504)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:1017)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:960)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:858)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:480)
    … 14 more
    Caused by: org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.springframework.orm.hibernate4.LocalSessionFactoryBean com.spring4hibernate.configuration.HibernateConfiguration.sessionFactory()] threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘dataSource’ defined in class path resource [com/spring4hibernate/configuration/HibernateConfiguration.class]: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public javax.sql.DataSource com.spring4hibernate.configuration.HibernateConfiguration.dataSource()] threw exception; nested exception is java.lang.IllegalStateException: required key [jdbc:oracle:thin:@localhost:1521:xe] not found
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:188)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:586)
    … 26 more
    Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘dataSource’ defined in class path resource [com/spring4hibernate/configuration/HibernateConfiguration.class]: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public javax.sql.DataSource com.spring4hibernate.configuration.HibernateConfiguration.dataSource()] threw exception; nested exception is java.lang.IllegalStateException: required key [jdbc:oracle:thin:@localhost:1521:xe] not found
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:597)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1094)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:989)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:504)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
    at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:324)
    at com.spring4hibernate.configuration.HibernateConfiguration$$EnhancerBySpringCGLIB$$5774b1a8.dataSource()
    at com.spring4hibernate.configuration.HibernateConfiguration.sessionFactory(HibernateConfiguration.java:38)
    at com.spring4hibernate.configuration.HibernateConfiguration$$EnhancerBySpringCGLIB$$5774b1a8.CGLIB$sessionFactory$1()
    at com.spring4hibernate.configuration.HibernateConfiguration$$EnhancerBySpringCGLIB$$5774b1a8$$FastClassBySpringCGLIB$$3e26a36c.invoke()
    at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
    at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:312)
    at com.spring4hibernate.configuration.HibernateConfiguration$$EnhancerBySpringCGLIB$$5774b1a8.sessionFactory()
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:166)
    … 27 more
    Caused by: org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public javax.sql.DataSource com.spring4hibernate.configuration.HibernateConfiguration.dataSource()] threw exception; nested exception is java.lang.IllegalStateException: required key [jdbc:oracle:thin:@localhost:1521:xe] not found
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:188)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:586)
    … 48 more
    Caused by: java.lang.IllegalStateException: required key [jdbc:oracle:thin:@localhost:1521:xe] not found
    at org.springframework.core.env.AbstractPropertyResolver.getRequiredProperty(AbstractPropertyResolver.java:104)
    at org.springframework.core.env.AbstractEnvironment.getRequiredProperty(AbstractEnvironment.java:490)
    at com.spring4hibernate.configuration.HibernateConfiguration.dataSource(HibernateConfiguration.java:49)
    at com.spring4hibernate.configuration.HibernateConfiguration$$EnhancerBySpringCGLIB$$5774b1a8.CGLIB$dataSource$3()
    at com.spring4hibernate.configuration.HibernateConfiguration$$EnhancerBySpringCGLIB$$5774b1a8$$FastClassBySpringCGLIB$$3e26a36c.invoke()
    at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
    at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:312)
    at com.spring4hibernate.configuration.HibernateConfiguration$$EnhancerBySpringCGLIB$$5774b1a8.dataSource()
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:166)
    … 49 more

  • deepak

    @PropertySource(value = {“classpath:application.properties”})..Do i need to specify my classpath to resource folder explicitly…need help!!

    • websystique

      No you don’t need to do anything special for resource folder.It is in classpath

  • Guilherme Marquesini Reis Ribe

    Thank you sir. It’s working . Good example

    • websystique

      Hey Guilherme,

      Glad it helped. Many Thanks for your feedback.

  • Ajeet Mohan

    I am running in Eclipse, getting exception on executing mail method, No bean named ‘employeeService’ is defined, I have added all the jars required… plz advice.

    • websystique

      Hey Ajeet, make sure to annotate your service implementation class with Spring annotation [@Service("employeeService")]

      • Nick Yashaev

        doesnt work for me too …it is annotated , and still nothing

        אוג 04, 2015 10:19:29 PM org.springframework.context.annotation.AnnotationConfigApplicationContext prepareRefresh
        INFO: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@685f4c2e: startup date [Tue Aug 04 22:19:29 IDT 2015]; root of context hierarchy
        Exception in thread “main” org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named ‘userService’ is defined
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:641)
        at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1157)
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:280)
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
        at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:973)
        at com.websystique.spring.AppMain.main(AppMain.java:17)

        here is the trace…

        • websystique

          Hi Nick, Are you sure you are not mixing up this project with other projects you might be working/trying on? We don’t have any userService in this project. We have only EmployeeSerivce.

          Look at above AppMain class, basically this line :

          EmployeeService service = (EmployeeService) context.getBean(“employeeService”);

          Download the project and try again please. Let me know if any issue.

          • Nick Yashaev

            i have done the same thing with the same annotations , just my class is called user and not employee…. and im having the same issue the first commenter had…

            the issue is that i dont understand this even if it supposed to work , HOW ?
            there is no “EmployeeManager” Bean defined at anyplace , how can we get that bean ?

          • websystique

            There is no EmployeeManager, but there is an EmployeeServiceImpl defined above with “employeeService”

            @service(“employeeService”)
            @Transactional
            public class EmployeeServiceImpl implements EmployeeService

            And this employeeService is then looked up in AppMain

            EmployeeService service = (EmployeeService) context.getBean(“employeeService”);

          • Somesh Jha

            Just make sure your AppConfig.java has basePackages which points to the common part of package. For example:
            if the package for service is com.test.spring.service and for model is com.test.spring.model, your base package will be com.test.spring

  • websystique

    Hi, Sorry for late reply. Yes the package is corrected now.The xml files can be named whatever you prefer.They are plain spring configuration files and can be placed in src/main/resources e.g.

  • Manjunath M

    Does all the set up will be same for linx as well.

    • websystique

      Hi Manjunath,

      Yes it should remain same.

  • Pingback: Spring mvc Java based Configuration not working. Console display no error but my jsp page is not showing | Solutions for enthusiast and professional programmers()

  • Mythul

    Great guide. Love it.

  • Evan Hu

    Thank you sir. It’s working very well in my local pc.