Maven + (Spring + Hibernate) Annotation + MySql Example

In last tutorial, you use Maven to create a simple Java project structure, and demonstrate how to use Hibernate in Spring framework to do the data manipulation works(insert, select, update and delete) in MySQL database. In this tutorial, you will learn how to do the same thing in Spring and Hibernate annotation way.

Prerequisite requirement

– Installed and configured Maven, MySQL, Eclipse IDE.

The javaee.jar library is required as well, you can get it from j2ee SDK, and include it manually, there is no full version of javaee.jar available in any of the Maven repository yet.

Final project structure

Your final project file structure should look exactly like following, if you get lost in the folder structure creation, please review this folder structure here.

1. Table creation

Create a ‘stock’ table in MySQL database. SQL statement as follow :


CREATE TABLE  `mkyong`.`stock` (
  `STOCK_ID` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `STOCK_CODE` varchar(10) NOT NULL,
  `STOCK_NAME` varchar(20) NOT NULL,
  PRIMARY KEY (`STOCK_ID`) USING BTREE,
  UNIQUE KEY `UNI_STOCK_NAME` (`STOCK_NAME`),
  UNIQUE KEY `UNI_STOCK_ID` (`STOCK_CODE`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8;

2. Project File Structure

Create a quick project file structure with Maven command ‘mvn archetype:generate‘, see example here. Convert it to Eclipse project (mvn eclipse:eclipse) and import it into Eclipse IDE.


E:\workspace>mvn archetype:generate
[INFO] Scanning for projects...
...
Choose a number:  
(1/2/3....) 15: : 15
...
Define value for groupId: : com.mkyong.common
Define value for artifactId: : HibernateExample
Define value for version:  1.0-SNAPSHOT: :
Define value for package:  com.mkyong.common: : com.mkyong.common
[INFO] OldArchetype created in dir: E:\workspace\HibernateExample
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESSFUL
[INFO] ------------------------------------------------------------------------

3. Pom.xml file configuration

Add the Spring, Hibernate, Annotation and MySQL and their dependency in the Maven’s pom.xml file.


<project xmlns="http://maven.apache.org/POM/4.0.0" 
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
  http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.mkyong.common</groupId>
  <artifactId>SpringExample</artifactId>
  <packaging>jar</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>SpringExample</name>
  <url>http://maven.apache.org</url>
  
  <repositories>
    <repository>
      <id>JBoss repository</id>
      <url>http://repository.jboss.com/maven2/</url>
    </repository>
  </repositories>
  
  <dependencies>
    
        <!-- JUnit testing framework -->
        <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>3.8.1</version>
                <scope>test</scope>
        </dependency>
    
        <!-- Spring framework -->
	<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring</artifactId>
		<version>2.5.6</version>
	</dependency>
    
        <!-- Spring AOP dependency -->
        <dependency>
    	        <groupId>cglib</groupId>
		<artifactId>cglib</artifactId>
		<version>2.2</version>
	</dependency>
    
        <!-- MySQL database driver -->
	<dependency>
		<groupId>mysql</groupId>
		<artifactId>mysql-connector-java</artifactId>
		<version>5.1.9</version>
	</dependency>
	
	<!-- Hibernate framework -->
	<dependency>
		<groupId>hibernate</groupId>
		<artifactId>hibernate3</artifactId>
		<version>3.2.3.GA</version>
	</dependency>
	
	<!-- Hibernate annotation -->
	<dependency>
		<groupId>hibernate-annotations</groupId>
		<artifactId>hibernate-annotations</artifactId>
		<version>3.3.0.GA</version>
	</dependency>
 
	<dependency>
		<groupId>hibernate-commons-annotations</groupId>
		<artifactId>hibernate-commons-annotations</artifactId>
		<version>3.0.0.GA</version>
	</dependency>
	
	<!-- Hibernate library dependecy start -->
	<dependency>
		<groupId>dom4j</groupId>
		<artifactId>dom4j</artifactId>
		<version>1.6.1</version>
	</dependency>
	
	<dependency>
		<groupId>commons-logging</groupId>
		<artifactId>commons-logging</artifactId>
		<version>1.1.1</version>
	</dependency>
	
	<dependency>
		<groupId>commons-collections</groupId>
		<artifactId>commons-collections</artifactId>
		<version>3.2.1</version>
	</dependency>
	
	<dependency>
		<groupId>antlr</groupId>
		<artifactId>antlr</artifactId>
		<version>2.7.7</version>
	</dependency>
	<!-- Hibernate library dependecy end -->
	
  </dependencies>
</project>

4. Model & BO & DAO

The Model, Business Object (BO) and Data Access Object (DAO) pattern is useful to identify the layer clearly to avoid mess up the project structure.

Stock Model (Annotation)

A Stock model annotation class to store the stock data.


package com.mkyong.stock.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;

@Entity
@Table(name = "stock", catalog = "mkyong", uniqueConstraints = {
		@UniqueConstraint(columnNames = "STOCK_NAME"),
		@UniqueConstraint(columnNames = "STOCK_CODE") })
public class Stock implements java.io.Serializable {

	private Integer stockId;
	private String stockCode;
	private String stockName;

	public Stock() {
	}

	public Stock(String stockCode, String stockName) {
		this.stockCode = stockCode;
		this.stockName = stockName;
	}

	@Id
	@GeneratedValue(strategy = IDENTITY)
	@Column(name = "STOCK_ID", unique = true, nullable = false)
	public Integer getStockId() {
		return this.stockId;
	}

	public void setStockId(Integer stockId) {
		this.stockId = stockId;
	}

	@Column(name = "STOCK_CODE", unique = true, nullable = false, length = 10)
	public String getStockCode() {
		return this.stockCode;
	}

	public void setStockCode(String stockCode) {
		this.stockCode = stockCode;
	}

	@Column(name = "STOCK_NAME", unique = true, nullable = false, length = 20)
	public String getStockName() {
		return this.stockName;
	}

	public void setStockName(String stockName) {
		this.stockName = stockName;
	}

	@Override
	public String toString() {
		return "Stock [stockCode=" + stockCode + ", stockId=" + stockId
				+ ", stockName=" + stockName + "]";
	}
}
Stock Business Object (BO))

Stock business object (BO) interface and implementation, it’s used to store the project’s business function, the real database operations (CRUD) works should not involved in this class, instead it has a DAO (StockDao) class to do it.


package com.mkyong.stock.bo;

import com.mkyong.stock.model.Stock;

public interface StockBo {
	
	void save(Stock stock);
	void update(Stock stock);
	void delete(Stock stock);
	Stock findByStockCode(String stockCode);
}

Make this class as a bean “stockBo” in Spring Ioc container, and autowire the stock dao class.


package com.mkyong.stock.bo.impl;

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

import com.mkyong.stock.bo.StockBo;
import com.mkyong.stock.dao.StockDao;
import com.mkyong.stock.model.Stock;

@Service("stockBo")
public class StockBoImpl implements StockBo{
	
	@Autowired
	StockDao stockDao;
	
	public void setStockDao(StockDao stockDao) {
		this.stockDao = stockDao;
	}

	public void save(Stock stock){
		stockDao.save(stock);
	}
	
	public void update(Stock stock){
		stockDao.update(stock);
	}
	
	public void delete(Stock stock){
		stockDao.delete(stock);
	}
	
	public Stock findByStockCode(String stockCode){
		return stockDao.findByStockCode(stockCode);
	}
}
Stock Data Access Object

A Stock DAO interface and implementation. In last tutorial, you DAO classes are directly extends the “HibernateDaoSupport“, but it’s not possible to do it in annotation mode, because you have no way to auto wire the session Factory bean from your DAO class. The workaround is create a custom class (CustomHibernateDaoSupport) and extends the “HibernateDaoSupport” and auto wire the session factory, and your DAO classes extends this class.


package com.mkyong.stock.dao;

import com.mkyong.stock.model.Stock;

public interface StockDao {
	
	void save(Stock stock);
	void update(Stock stock);
	void delete(Stock stock);
	Stock findByStockCode(String stockCode);

}

package com.mkyong.util;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

public abstract class CustomHibernateDaoSupport extends HibernateDaoSupport
{    
    @Autowired
    public void anyMethodName(SessionFactory sessionFactory)
    {
        setSessionFactory(sessionFactory);
    }
}

package com.mkyong.stock.dao.impl;

import java.util.List;

import org.springframework.stereotype.Repository;

import com.mkyong.stock.dao.StockDao;
import com.mkyong.stock.model.Stock;
import com.mkyong.util.CustomHibernateDaoSupport;

@Repository("stockDao")
public class StockDaoImpl extends CustomHibernateDaoSupport implements StockDao{
	
	public void save(Stock stock){
		getHibernateTemplate().save(stock);
	}
	
	public void update(Stock stock){
		getHibernateTemplate().update(stock);
	}
	
	public void delete(Stock stock){
		getHibernateTemplate().delete(stock);
	}
	
	public Stock findByStockCode(String stockCode){
		List list = getHibernateTemplate().find(
                     "from Stock where stockCode=?",stockCode
                );
		return (Stock)list.get(0);
	}

}

5. Resource Configuration

Create a ‘resources‘ folder under ‘project_name/main/java/‘, Maven will treat all files under this folder as resources file. It will used to store the Spring, Hibernate and others configuration file.

Spring Configuration

Database related….

Create a properties file (database.properties) for the database details, put it into the “resources/properties” folder. It’s good practice disparate the database details and Spring bean configuration into different files.

database.properties


jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mkyong
jdbc.username=root
jdbc.password=password

Create a “dataSource” bean configuration file (DataSource.xml) for your database, and import the properties from database.properties, put it into the “resources/database” folder.

DataSource.xml


<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
	
<bean 
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
	<property name="location">
		<value>properties/database.properties</value>
	</property>
</bean>

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

</beans>

Hibernate related….

Create a session factory bean configuration file (Hibernate.xml), put it into the “resources/database” folder. In annotation you have to use the AnnotationSessionFactoryBean, instead of LocalSessionFactoryBean, and specify your annotated model classes in ‘annotatedClasses‘ property instead of ‘mappingResources‘ property.

Hibernate.xml


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
    
<!-- Hibernate session factory -->
<bean id="sessionFactory" 
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">

    <property name="dataSource">
      <ref bean="dataSource"/>
    </property>

    <property name="hibernateProperties">
       <props>
         <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
         <prop key="hibernate.show_sql">true</prop>
       </props>
    </property>
    	
    <property name="annotatedClasses">
	<list>
		<value>com.mkyong.stock.model.Stock</value>
	</list>
    </property>

    </bean>
</beans>    

Import all the Spring’s beans configuration files into a single file (BeanLocations.xml), put it into the “resources/config” folder.

BeanLocations.xml
Import the Spring database configuration and enable the Spring’s auto scan feature.


<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-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">

	<!-- Database Configuration -->
	<import resource="../database/DataSource.xml"/>
	<import resource="../database/Hibernate.xml"/>
	
	<!-- Auto scan the components -->
	<context:component-scan 
		base-package="com.mkyong.stock" />
	
</beans>

6. Run it

You have all the files and configurations , run it.


package com.mkyong.common;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.mkyong.stock.bo.StockBo;
import com.mkyong.stock.model.Stock;

public class App 
{
    public static void main( String[] args )
    {
    	ApplicationContext appContext = 
    	  new ClassPathXmlApplicationContext("spring/config/BeanLocations.xml");
	
    	StockBo stockBo = (StockBo)appContext.getBean("stockBo");
    	
    	/** insert **/
    	Stock stock = new Stock();
    	stock.setStockCode("7668");
    	stock.setStockName("HAIO");
    	stockBo.save(stock);
    	
    	/** select **/
    	Stock stock2 = stockBo.findByStockCode("7668");
    	System.out.println(stock2);
    	
    	/** update **/
    	stock2.setStockName("HAIO-1");
    	stockBo.update(stock2);
    	
    	/** delete **/
    	stockBo.delete(stock2);
    	
    	System.out.println("Done");
    }
}

output


Hibernate: insert into mkyong.stock (STOCK_CODE, STOCK_NAME) values (?, ?)
Hibernate: select stock0_.STOCK_ID as STOCK1_0_, 
stock0_.STOCK_CODE as STOCK2_0_, stock0_.STOCK_NAME as STOCK3_0_ 
from mkyong.stock stock0_ where stock0_.STOCK_CODE=?
Stock [stockCode=7668, stockId=11, stockName=HAIO]
Hibernate: update mkyong.stock set STOCK_CODE=?, STOCK_NAME=? where STOCK_ID=?
Hibernate: delete from mkyong.stock where STOCK_ID=?
Done

Conclusion

All Spring, Hibernate related classes and configuration files are annotated, it just left the database details in XML file. Should you know how to annotate the database configuration details, please let me know. Personally, i do not use annotation feature much, because somehow you may need some workaround for certain situation, like ‘CustomHibernateDaoSupport’ extends ‘HibernateDaoSupport’ above. The mature developed XML file in Spring and Hibernate. is more preferably.

149 comments on “Maven + (Spring + Hibernate) Annotation + MySql Example

  1. Hi, Can you just reply whether the same hibernate integration approach will work in spring boot 2.0.2 version?

    Reply
  2. is it necessary to make configuration by xml file. is it possible to make complete configuration through annotations.

    Reply
  3. I tried following along with this program for my own web mvc application and getting the error “No bean named ‘stockBo’ available”. I’ve looked everywhere online and tried a number of combinations changing my web.xml, spring-mvc.xml, spring-config.xml and some annotation changes but nothing is working. Any clues?

    Reply
  4. Hello . Can you please update it Spring 3 and Hibernate 4! By the way it’s Great Work!

    Reply
  5. Failed to convert property value of type ‘java.util.ArrayList’ to required type ‘java.lang.Class[]’ for property ‘annotatedClasses’

    unable to run please help

    Reply
  6. thank you. Could you please do the same great example using the latest hibernate and latest spring?

    Reply
  7. Thanks for the tutorilal. when i am trying to run app.java i am getting following error. This is because auto intrement coloumn not getting populated.

    Exception in thread “main” org.springframework.jdbc.UncategorizedSQLException: Hibernate operation: could not insert: [com.mkyong.stock.model.Stock]; uncategorized SQLException for SQL [insert into stock1 (STOCK_CODE, STOCK_NAME) values (?, ?)]; SQL state [99999]; error code [17004]; Invalid column type: getInt not implemented for class oracle.jdbc.driver.T4CRowidAccessor; nested exception is java.sql.SQLException: Invalid column type: getInt not implemented for class oracle.jdbc.driver.T4CRowidAccessor
    at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:83)
    at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:80)
    at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:80)
    at org.springframework.orm.hibernate3.HibernateAccessor.convertJdbcAccessException(HibernateAccessor.java:424)
    at org.springframework.orm.hibernate3.HibernateAccessor.convertHibernateAccessException(HibernateAccessor.java:410)
    at org.springframework.orm.hibernate3.HibernateTemplate.doExecute(HibernateTemplate.java:424)
    at org.springframework.orm.hibernate3.HibernateTemplate.executeWithNativeSession(HibernateTemplate.java:374)
    at org.springframework.orm.hibernate3.HibernateTemplate.save(HibernateTemplate.java:694)
    at com.mkyong.stock.dao.impl.StockDaoImpl.save(StockDaoImpl.java:17)
    at com.mkyong.stock.bo.dao.impl.StockBoImpl.save(StockBoImpl.java:21)
    at com.mkyong.stock.model.App.main(App.java:18)
    Caused by: java.sql.SQLException: Invalid column type: getInt not implemented for class oracle.jdbc.driver.T4CRowidAccessor
    at oracle.jdbc.driver.Accessor.unimpl(Accessor.java:412)
    at oracle.jdbc.driver.Accessor.getInt(Accessor.java:529)
    at oracle.jdbc.driver.OracleReturnResultSet.getInt(OracleReturnResultSet.java:388)
    at org.hibernate.id.IdentifierGeneratorFactory.get(IdentifierGeneratorFactory.java:50)
    at org.hibernate.id.IdentifierGeneratorFactory.getGeneratedIdentity(IdentifierGeneratorFactory.java:35)
    at org.hibernate.id.IdentityGenerator$GetGeneratedKeysDelegate.executeAndExtract(IdentityGenerator.java:74)
    at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:33)
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2158)
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2638)
    at org.hibernate.action.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:48)
    at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:248)
    at org.hibernate.event.def.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:298)
    at org.hibernate.event.def.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:181)
    at org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:107)
    at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:187)
    at org.hibernate.event.def.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:33)
    at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:172)
    at org.hibernate.event.def.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:27)
    at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:70)
    at org.hibernate.impl.SessionImpl.fireSave(SessionImpl.java:535)
    at org.hibernate.impl.SessionImpl.save(SessionImpl.java:523)
    at org.hibernate.impl.SessionImpl.save(SessionImpl.java:519)
    at org.springframework.orm.hibernate3.HibernateTemplate$12.doInHibernate(HibernateTemplate.java:697)
    at org.springframework.orm.hibernate3.HibernateTemplate.doExecute(HibernateTemplate.java:419)
    … 5 more

    Reply
  8. The pom file doesnt work….include this

    org.hibernate

    hibernate-entitymanager

    4.3.8.Final

    Reply
  9. the pom file is this project will not run correctly….try including this dependency…

    org.hibernate
    hibernate-entitymanager
    4.3.8.Final

    Reply
  10. I try to add JSF 2 in this project, but i’ve a lot of problems, it’s very hard to do it.

    I think a structure of projet is differente

    Reply
  11. Hello,

    My problem is that Eclipse doesnt know import javax.persistence.Column and others imports in Class Model and annotations in class Model I dont know why, please any help.

    Reply
    1. org.hibernate.javax.persistence
      hibernate-jpa-2.0-api
      1.0.1.Final

      javax.persistence
      persistence-api
      1.0

      Reply
  12. hello to you i’m learning how to use Spring Framework but i’ve some problems with this tutorial. When i launch the example builded i always encounter the same problem. Can someone help me please ? the message shown by Spring Tool Suite in the following :

    sept. 20, 2014 11:28:13 AM org.springframework.context.support.AbstractApplicationContext prepareRefresh

    INFOS: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@171fc7e: startup date [Sat Sep 20 11:28:12 WAT 2014]; root of context hierarchy

    sept. 20, 2014 11:28:13 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions

    INFOS: Loading XML bean definitions from class path resource [spring/config/BeansLocations.xml]

    sept. 20, 2014 11:28:13 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions

    INFOS: Loading XML bean definitions from class path resource [spring/database/DataSource.xml]

    sept. 20, 2014 11:28:13 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions

    INFOS: Loading XML bean definitions from class path resource [spring/database/Hibernate.xml]

    sept. 20, 2014 11:28:14 AM org.springframework.core.io.support.PropertiesLoaderSupport loadProperties

    INFOS: Loading properties file from class path resource [properties/database.properties]

    sept. 20, 2014 11:28:14 AM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons

    INFOS: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@1494225: defining beans [org.springframework.beans.factory.config.PropertyPlaceholderConfigurer#0,dataSource,sessionFactory,stockBo,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.internalPersistenceAnnotationProcessor,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor]; root of factory hierarchy

    Exception in thread “main” java.lang.NoSuchMethodError: org.springframework.beans.factory.annotation.InjectionMetadata.(Ljava/lang/Class;)V

    at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.findPersistenceMetadata(PersistenceAnnotationBeanPostProcessor.java:350)

    at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.postProcessMergedBeanDefinition(PersistenceAnnotationBeanPostProcessor.java:296)

    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyMergedBeanDefinitionPostProcessors(AbstractAutowireCapableBeanFactory.java:840)

    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:495)

    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458)

    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)

    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)

    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)

    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)

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

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

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

    at org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:139)

    at org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:83)

    at com.mkyong.common.App.main(App.java:13)

    App.main is my main class

    Thanks

    Reply
  13. Hi i am getting below exception
    Caused by: java.lang.ClassNotFoundException: org.aopalliance.intercept.MethodInterceptor

    Reply
  14. I tried to run this in Eclipse. I did “Run as > Maven build” with “clean install” in the target line. It built correctly and ran the unit tests, but it didn’t execute. I tried pressing the green eclipse button, but it doesn’t seem to know to run App.java. I looked under External tools and didn’t find the command line. I’m using Eclipse Kepler.

    Reply
  15. Hi, good tuto thanks for your effort, but i have question about how can i automatically generate table by using Hibernate, can you help me plz

    Reply
  16. Hi! I´ve my hibernate configuration inside my spring-context, but after a little time of use I´m getting the too many connections error. Here is my code:

    Spring context:

    com.proximate.model.Usuarios

    org.hibernate.dialect.MySQLDialect

    true

    true

    and here is how I use my session factory inside my dao:

    private SessionFactory sessionFactory;

    private HibernateTemplate hibernateTemplate;

    public SessionFactory getSessionFactory() {

    return sessionFactory;

    }

    public void setSessionFactory(SessionFactory sessionFactory) {

    this.hibernateTemplate = new HibernateTemplate(sessionFactory);

    }

    Query query = hibernateTemplate.getSessionFactory().getCurrentSession().createSQLQuery(“SELECT ID FROM usuarios”);

    Integer cantidad = new Integer(((BigInteger) query.uniqueResult()).intValue());

    Why is my code opening so many connections. I heard that using a HibernateUtil class to load a session after logging might be what I need, but how do you implement it when using spring??

    Thanks in advance!!

    Reply
  17. guys, I’m hitting the wall with this exception ” java.lang.ClassNotFoundException: javax.annotation.CheckReturnValue” just after trying to run the App file, can anyone help plz

    Reply
  18. Hi, I write my small contribution:

    We have to change 2 dependences in pom.xml

    	<dependency>
    		<groupId>org.hibernate</groupId>
    		<artifactId>hibernate-annotations</artifactId>
    		<version>3.3.0.ga</version>
    	</dependency>
     
    	<dependency>
    		<groupId>org.hibernate</groupId>
    		<artifactId>hibernate-commons-annotations</artifactId>
    		<version>3.0.0.ga</version>
    	</dependency>
    

    BONUS:
    if you want to install javaee.jar in your repository just execute the next program on shell:

    mvn install:install-file -Dfile= -DgroupId=org.javax -DartifactId=javaee -Dversion=1.0 -Dpackaging=jar

    then in pom.xml put the next dependency:

        <dependency>
          <groupId>org.javax</groupId>
          <artifactId>javaee</artifactId>
          <version>1.0</version>
        </dependency>
    

    thank for advice.
    CharlyR

    Reply
    1. the command was bad edited, please use this example:

      mvn install:install-file -Dfile=./src/main/resources/javaee.jar -DgroupId=org.javax -DartifactId=javaee -Dversion=1.0 -Dpackaging=jar

      Reply
  19. “In last tutorial, you DAO classes are directly extends the “HibernateDaoSupport“, but it’s not possible to do it in annotation mode, because you have no way to auto wire the session Factory bean from your DAO class.”

    It works for me:

    package com.mkyong.stock.dao.impl;
    
    import java.util.List;
    
    import org.hibernate.SessionFactory;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
    import org.springframework.stereotype.Repository;
    
    import com.mkyong.stock.dao.StockDao;
    import com.mkyong.stock.model.Stock;
    import com.mkyong.util.CustomHibernateDaoSupport;
    
    @Repository("stockDao")
    public class StockDaoImpl extends HibernateDaoSupport implements StockDao{
    	
    	@Autowired
        public void anyMethodName(SessionFactory sessionFactory)
        {
            setSessionFactory(sessionFactory);
        }
    	
    	public void save(Stock stock){
    		getHibernateTemplate().save(stock);
    	}
    	
    	public void update(Stock stock){
    		getHibernateTemplate().update(stock);
    	}
    	
    	public void delete(Stock stock){
    		getHibernateTemplate().delete(stock);
    	}
    	
    	public Stock findByStockCode(String stockCode){
    		List list = getHibernateTemplate().find("from Stock where stockCode=?",stockCode);
    		return (Stock)list.get(0);
    	}
    
    }
    
    Reply
  20. “A Stock DAO interface and implementation. In last tutorial, you DAO classes are directly extends the “HibernateDaoSupport“, but it’s not possible to do it in annotation mode, because you have no way to auto wire the session Factory bean from your DAO class.”

    It works for me:

    package com.mkyong.stock.dao.impl;
    
    import java.util.List;
    
    import org.hibernate.SessionFactory;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
    import org.springframework.stereotype.Repository;
    
    import com.mkyong.stock.dao.StockDao;
    import com.mkyong.stock.model.Stock;
    import com.mkyong.util.CustomHibernateDaoSupport;
    
    @Repository("stockDao")
    public class StockDaoImpl extends HibernateDaoSupport implements StockDao{
    	
    @Autowired
        public void anyMethodName(SessionFactory sessionFactory)
        {
            setSessionFactory(sessionFactory);
        }
    	
    	public void save(Stock stock){
    		getHibernateTemplate().save(stock);
    	}
    	
    	public void update(Stock stock){
    		getHibernateTemplate().update(stock);
    	}
    	
    	public void delete(Stock stock){
    		getHibernateTemplate().delete(stock);
    	}
    	
    	public Stock findByStockCode(String stockCode){
    		List list = getHibernateTemplate().find("from Stock where stockCode=?",stockCode);
    		return (Stock)list.get(0);
    	}
    
    }
    
    Reply
  21. Hi .thanks for this post, it’s very useful.
    Question : how do we host maven + spring + hibernate in GAE?

    Reply
    1. Hi. is there an easier way to automatically scan and use any @Entity marked objects instead of listing all of them in a sessionFactory using

      ??

      Reply
  22. Can u are tell me, why i am gating these error:

    Feb 19, 2013 4:51:58 PM org.apache.catalina.core.AprLifecycleListener init
    INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: C:\Program Files\Java\jre7\bin;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files\TortoiseSVN\bin;C:\Program Files\Java\jdk1.6.0_32\bin;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;.
    Feb 19, 2013 4:52:02 PM org.apache.tomcat.util.digester.SetPropertiesRule begin
    WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property ‘source’ to ‘org.eclipse.jst.jee.server:SpringTest’ did not find a matching property.
    Feb 19, 2013 4:52:11 PM org.apache.coyote.http11.Http11Protocol init
    INFO: Initializing Coyote HTTP/1.1 on http-8080
    Feb 19, 2013 4:52:11 PM org.apache.catalina.startup.Catalina load
    INFO: Initialization processed in 21829 ms
    Feb 19, 2013 4:52:12 PM org.apache.catalina.core.StandardService start
    INFO: Starting service Catalina
    Feb 19, 2013 4:52:12 PM org.apache.catalina.core.StandardEngine start
    INFO: Starting Servlet Engine: Apache Tomcat/6.0.32
    Feb 19, 2013 4:52:15 PM org.apache.catalina.core.StandardContext listenerStart
    SEVERE: Error configuring application listener of class org.springframework.web.context.ContextLoaderListener
    java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1680)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1526)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4148)
    at org.apache.catalina.core.StandardContext.start(StandardContext.java:4704)
    at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1053)
    at org.apache.catalina.core.StandardHost.start(StandardHost.java:840)
    at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1053)
    at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:463)

    Reply
  23. Hi everyone/Mkyong.com

    I configured new SpringIDE with Maven and i want to write simple web based application.but when i am going to run my application ,there,it was showing some error(I attached in below)whereas ,without SpringIDE and Maven it was ok….

    I already checked these solution;

    A>In web.xml ,ContextLoaderListener is configured or not.
    B> I am using these software
    1.eclipse-jee-juno-win32-x86_64
    2.apache-maven-3.0.4-bin,
    3.OS Window7-64bit

    Can u are tell me, why i am gating these error:

    Feb 19, 2013 4:51:58 PM org.apache.catalina.core.AprLifecycleListener init
    INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: C:\Program Files\Java\jre7\bin;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files\TortoiseSVN\bin;C:\Program Files\Java\jdk1.6.0_32\bin;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;.
    Feb 19, 2013 4:52:02 PM org.apache.tomcat.util.digester.SetPropertiesRule begin
    WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property ‘source’ to ‘org.eclipse.jst.jee.server:SpringTest’ did not find a matching property.
    Feb 19, 2013 4:52:11 PM org.apache.coyote.http11.Http11Protocol init
    INFO: Initializing Coyote HTTP/1.1 on http-8080
    Feb 19, 2013 4:52:11 PM org.apache.catalina.startup.Catalina load
    INFO: Initialization processed in 21829 ms
    Feb 19, 2013 4:52:12 PM org.apache.catalina.core.StandardService start
    INFO: Starting service Catalina
    Feb 19, 2013 4:52:12 PM org.apache.catalina.core.StandardEngine start
    INFO: Starting Servlet Engine: Apache Tomcat/6.0.32
    Feb 19, 2013 4:52:15 PM org.apache.catalina.core.StandardContext listenerStart
    SEVERE: Error configuring application listener of class org.springframework.web.context.ContextLoaderListener
    java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1680)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1526)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4148)
    at org.apache.catalina.core.StandardContext.start(StandardContext.java:4704)
    at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1053)
    at org.apache.catalina.core.StandardHost.start(StandardHost.java:840)
    at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1053)
    at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:463)

    Reply
  24. This tutorial is quiet outdated now. Can you please update it Spring 3 and Hibernate 4

    Reply
  25. Hey, do you have an idea about this problem?? I can not unlock it demoralizes me: s

    Thank you in advance

    org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘sessionFactory’ defined in ServletContext resource [/WEB-INF/classes/config/spring/HibernateSessionFactory.xml]: Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property ‘annotatedClasses’ of bean class [org.springframework.orm.hibernate3.LocalSessionFactoryBean]: Bean property ‘annotatedClasses’ is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?

    Reply
    1. this is resolved I should use AnnotationSessionFactoryBean – Tks Mkyong For All

      Reply
  26. Hi Mkyong,

    A very good example to understand the Spring + hibernate integration.
    But as i was trying to build your project following errors are coming. Please help

    D:\Project\SpringHibernateAnnotationExample\src\main\java\com\mkyong\util\CustomHibernateDaoSupport.java:[9,2] error: annotations are not supported in -source 1.3

    could not parse error message: (use -source 5 or higher to enable annotations)
    D:\Project\SpringHibernateAnnotationExample\src\main\java\com\mkyong\stock\bo\impl\StockBoImpl.java:10: error: annotations are not supported in -source 1.3
    @Service(“stockBo”)
    ^

    could not parse error message: (use -source 5 or higher to enable annotations)
    D:\Project\SpringHibernateAnnotationExample\src\main\java\com\mkyong\stock\dao\impl\StockDaoImpl.java:11: error: annotations are not supported in -source 1.3
    @Repository(“stockDao”)
    ^

    could not parse error message: (use -source 5 or higher to enable annotations)
    D:\Project\SpringHibernateAnnotationExample\src\main\java\com\mkyong\stock\model\Stock.java:6: error: static import declarations are not supported in -source 1.3
    import static javax.persistence.GenerationType.IDENTITY;
    ^

    could not parse error message: (use -source 5 or higher to enable static import declarations)
    D:\Project\SpringHibernateAnnotationExample\src\main\java\com\mkyong\stock\model\Stock.java:11: error: annotations are not supported in -source 1.3
    @Entity
    ^

    Please help me in this direction.

    Thanks
    Varun

    Reply
  27. Nice Tutorial.

    But can’t able to download the maven dependencies. Mr.Yong, please kindly update this tutorial with latest repository urls.

    Thanks,
    Hariharan

    Reply
  28. good tutorial Thanks for sharing the information about JAVA EE in you’re webSite

    Reply
  29. This is a very good tutorial, I was able to follow it within Netbeans.

    Reply
  30. i got my solution….

    thank u for this gr8 example……

    Reply
  31. hi…
    plz help me i got stuck at this point.

    Exception in thread “main” org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘sessionFactory’ defined in class path resource [spring/database/Hibernate.xml]: Invocation of init method failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [org.hibernate.cfg.AnnotationConfiguration]: Constructor threw exception; nested exception is java.lang.NoSuchMethodError: org.slf4j.helpers.MessageFormatter.format(Ljava/lang/String;Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/String;
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1338)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:473)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory$1.run(AbstractAutowireCapableBeanFactory.java:409)
    at java.security.AccessController.doPrivileged(Native Method)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:380)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:264)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:261)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:185)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:164)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:423)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:728)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:380)
    at org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:139)
    at org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:83)
    at com.mkyong.common.App.main(App.java:14)
    Caused by: org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [org.hibernate.cfg.AnnotationConfiguration]: Constructor threw exception; nested exception is java.lang.NoSuchMethodError: org.slf4j.helpers.MessageFormatter.format(Ljava/lang/String;Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/String;
    at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:115)
    at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:78)
    at org.springframework.orm.hibernate3.LocalSessionFactoryBean.newConfiguration(LocalSessionFactoryBean.java:772)
    at org.springframework.orm.hibernate3.LocalSessionFactoryBean.buildSessionFactory(LocalSessionFactoryBean.java:517)
    at org.springframework.orm.hibernate3.AbstractSessionFactoryBean.afterPropertiesSet(AbstractSessionFactoryBean.java:211)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1369)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1335)
    … 15 more
    Caused by: java.lang.NoSuchMethodError: org.slf4j.helpers.MessageFormatter.format(Ljava/lang/String;Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/String;

    Reply
    1. @chandan Kumar…

      I too am getting the same error…
      Exception in thread “main” org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘sessionFactory’ defined in class path resource [spring/database/Hibernate.xml]: Invocation of init method failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [org.hibernate.cfg.AnnotationConfiguration]: Constructor threw exception; nested exception is

      Not able to get this fixed. Were you able to fix this Issue? Please share

      Thanks,
      Ravi

      Reply
      1. I have the same error, please help me

        Thank you for this genios tutorial

        Reply
  32. I did not understand at what point is triggered at the beginning of Spring and the end of the transaction to the business object. In the config file is not visible. Can you explain in your example?

    Reply
  33. Thanks for the article. It helped me to get started with an Hibernate app quite easily.

    Reply
  34. Hi! Please tell me and what I must choose the project number, if I carry on the development in the NetBeans IDE?

    Reply
  35. Hello. Please, help me. I’ve got an error:

    Could not autowire method: public void ua.kharkov.infostroy.test.bll.dao.HibernateDaoSupportImpl.anyMethodName(org.hibernate.SessionFactory); nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [org.hibernate.SessionFactory] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency.

    Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'IUserDAO': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire method: public void ua.kharkov.infostroy.test.bll.dao.HibernateDaoSupportImpl.anyMethodName(org.hibernate.SessionFactory); nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [org.hibernate.SessionFactory] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
    	at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:283)
    	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1055)
    	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:511)
    	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:450)
    	at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:290)
    	at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    	at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:287)
    	at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:189)
    	at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:557)
    	at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:842)
    	at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:416)
    	at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
    	at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
    	at ua.kharkov.infostroy.test.bll.controllers.Runner.main(Runner.java:14)
    Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire method: public void ua.kharkov.infostroy.test.bll.dao.HibernateDaoSupportImpl.anyMethodName(org.hibernate.SessionFactory); nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [org.hibernate.SessionFactory] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
    	at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.inject(AutowiredAnnotationBeanPostProcessor.java:605)
    	at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:84)
    	at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:280)
    	... 13 more
    Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [org.hibernate.SessionFactory] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
    	at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:896)
    	at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:765)
    	at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:680)
    	at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.inject(AutowiredAnnotationBeanPostProcessor.java:556)
    	... 15 more

    Thanks! Regards, Bogdan.
    P.S.: Your tutorial are really great!!!

    Reply
  36. I was using your other example (https://mkyong.com/jsf2/jsf-2-0-spring-hibernate-integration-example/) it’s working fine, ,now I modified the same example to use annotations, everything is fine except when the execution reaches the dao layer(getHibernateTemplate().save(), etc), it gets a null pointer exception, i.e it’s not able to get the session value. what could be the reason?

    Btw your tutorials are a big help…. thanks

    Reply
    1. I also included :

      @Autowired(required=true)
          public void anyMethodName(@Qualifier("sessionFactory")SessionFactory  sessionFactory)
          {
              setSessionFactory(sessionFactory);
          }
      
      

      But there is nochange in result.

      Reply
  37. Hi,

    Can you please let me know how to enable caching in this application..

    Thanks
    Shirish

    Reply
  38. Thank you !
    But if I am developping a Dynamic Web Project using JSF 2.0 ,
    I will need an applicationContext.xml ,
    what would be the content of this file?

    Reply
  39. you need to include ,
    jta.jar in pom.xml

     
              javax.transaction
              jta
              1.1
          
    
    Reply
  40. Hi ,

    I need a simple hibernate project without maven or ant and i need to run it in apache tomcat server in eclipse.

    Could you help me out with a link.

    Thanks in advance

    Reply
  41. Kindly, please support me.
    How to resolve this folloewing Error:
    ” The type org.springframework.dao.DataAccessException cannot be resolved. It is indirectly referenced from required .class files”

    which i wrote code is:

    Java –

     
    package com.srijen.DAO;
    import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
    import com.srijen.exception.StudentException;
    import com.srijen.model.Student;
    
    public class StudentDAOImpl extends HibernateDaoSupport implements StudentDAO {
    
    public void insertStudent(Student student) throws StudentException{
    		//getHibernateTemplate().save(student);
    		getHibernateTemplate().save(student);
    }
    }
    

    It is showing the above mentioned error & also:
    The hierarchy of the type StudentDAOImpl is inconsistent

    Reply
  42. Also, in the class

    public abstract class CustomHibernateDaoSupport extends HibernateDaoSupport
    {    
        @Autowired
        public void anyMethodName(SessionFactory sessionFactory)
        {
            setSessionFactory(sessionFactory);
        }
    }
    

    What is actually happening here? We are autowiring SessionFactory. Isn’t that true.

    If that is correct, then why can’t we declare it as below

    public class StockDaoImpl extends HibernateDaoSupport implements StockDao{
    
       @Autowired
       SessionFactory sessionFactory
       .................
    }
    

    ofcourse, I could not get this work. But curious in what way this declaration is different from what is declared in the post. Field autowiring vs method autowiring.

    Reply
    1. Yes, you can extend the HibernateDaoSupport directly, but if any major DAO support is changed (may be you don’t want to use Hibernate now), all codes need to change accordingly. To create a extra DAO support class, you just need to maintain one DAO support file.

      Either ways will works, just choose one to suit your needs 🙂

      Reply
  43. Your posts are really helpful in understanding the concepts and keep up the good work.

    I have a question here though, we actually annotated using @Service and @Repository but we are doing component scan. Are Service and Repository also considered as Components. If that is case, would that be wrong, if I use @Component instead of @Service and @Repository

    Reply
  44. Hi..This is my first comment in this website. And i have been following all the tutorials they are indeed great and very useful.

    While going through this tutorial and the previous one(w/o annotations) I saw you have separated the Bo layer and DAO layer. I don’t find the difference between both the layers and moreover both the interfaces (Bo and Dao) are exposing the same operations, can you please explain why do we need these two layers with a good example?

    Hope you will respond soon.

    Many Thanks…!
    Babu

    Reply
  45. thanks,
    found this example v useful.

    tbh its not the first time I use great pages from mkyong!

    Reply
  46. Just went through this, thanks for the example. A couple issues I had:

    1. The database.properties file somehow was not getting resolved, so eventually I just hard-coded those particular name-value pairs into DataSource.xml. Still not sure what the issue was.

    2. Thanks to one of the posters above, the correct maven POM is very important here, so I am posting the exact one I used below:

    <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.mkyong.common</groupId>
      <artifactId>HibernateSpringExample</artifactId>
      <version>1.0-SNAPSHOT</version>
      <packaging>jar</packaging>
    
      <name>HibernateSpringExample</name>
      <url>http://maven.apache.org</url>
    
      <repositories>
        <repository>
          <id>JBoss repository</id>
          <url>https://repository.jboss.org/nexus/content/groups/public-jboss/</url>
        </repository>
      </repositories>
      
      <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      </properties>
    
      <dependencies>
        <dependency>
          <groupId>junit</groupId>
          <artifactId>junit</artifactId>
          <version>3.8.1</version>
          <scope>test</scope>
        </dependency>
    	
            <!-- Spring framework -->
    	<dependency>
    		<groupId>org.springframework</groupId>
    		<artifactId>spring</artifactId>
    		<version>2.5.6</version>
    	</dependency>
     
            <!-- Spring AOP dependency -->
            <dependency>
        	        <groupId>cglib</groupId>
    		<artifactId>cglib</artifactId>
    		<version>2.2</version>
    	</dependency>
     
            <!-- MySQL database driver -->
    	<dependency>
    		<groupId>mysql</groupId>
    		<artifactId>mysql-connector-java</artifactId>
    		<version>5.1.9</version>
    	</dependency>
     
    	<!-- Hibernate framework -->
    	
    	<dependency>
    		<groupId>org.hibernate</groupId>
    		<artifactId>hibernate-core</artifactId>
    		<version>3.6.0.Final</version>
    	</dependency>
    
    	<!-- Hibernate annotation -->
    	<dependency>
    		<groupId>org.hibernate</groupId>
    		<artifactId>hibernate-tools</artifactId>
    		<version>3.2.3.GA</version>
    	</dependency>
     
    	<dependency>
    		<groupId>org.hibernate</groupId>
    		<artifactId>hibernate-commons-annotations</artifactId>
    		<version>3.2.0.Final</version>
    	</dependency>
     
    	<!-- Hibernate library dependency start -->
    	
    	<dependency>
    		<groupId>org.slf4j</groupId>
    		<artifactId>slf4j-log4j12</artifactId>
    		<version>1.5.8</version>
    	</dependency>
    
    	<dependency>
    		<groupId>javassist</groupId>
    		<artifactId>javassist</artifactId>
    		<version>3.4.GA</version>
    	</dependency>
    	
    	<dependency>
    		<groupId>dom4j</groupId>
    		<artifactId>dom4j</artifactId>
    		<version>1.6.1</version>
    	</dependency>
     
    	<dependency>
    		<groupId>commons-logging</groupId>
    		<artifactId>commons-logging</artifactId>
    		<version>1.1.1</version>
    	</dependency>
     
    	<dependency>
    		<groupId>commons-collections</groupId>
    		<artifactId>commons-collections</artifactId>
    		<version>3.2.1</version>
    	</dependency>
     
    	<dependency>
    		<groupId>antlr</groupId>
    		<artifactId>antlr</artifactId>
    		<version>2.7.7</version>
    	</dependency>
    	<!-- Hibernate library dependency end -->
    	
      </dependencies>
    </project>
    
    Reply
    1. 1. Make sure “database.properties” is put at the correct folder.
      2. Thanks for your input. Is my pom.xml in the download project not working?

      Reply
      1. I did not try the POM from the download folder, as I wanted to take things step by step….

        re: database.properties – tried it in the folder recommended above, and when that did not work, I tried moving it around (including to “src” which in eclipse should have been on the classpath). No big deal 🙂

        Thanks again for the tutorials, they are very good.

        Reply
    2. Exception in thread “main” java.lang.NoClassDefFoundError: Ljavax/transaction/TransactionManager;

      at java.lang.Class.getDeclaredFields0(Native Method)

      at java.lang.Class.privateGetDeclaredFields(Unknown Source)

      at java.lang.Class.getDeclaredFields(Unknown Source)

      at org.springframework.util.ReflectionUtils.doWithFields(ReflectionUtils.java:516)

      at org.springframework.util.ReflectionUtils.doWithFields(ReflectionUtils.java:500)

      at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.findPersistenceMetadata(PersistenceAnnotationBeanPostProcessor.java:351)

      at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.postProcessMergedBeanDefinition(PersistenceAnnotationBeanPostProcessor.java:296)

      at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyMergedBeanDefinitionPostProcessors(AbstractAutowireCapableBeanFactory.java:745)

      at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:448)

      at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory$1.run(AbstractAutowireCapableBeanFactory.java:409)

      at java.security.AccessController.doPrivileged(Native Method)

      at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:380)

      at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:264)

      at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)

      at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:261)

      at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:185)

      at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:164)

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

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

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

      at org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:139)

      at org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:83)

      at com.mkyong.common.App.main(App.java:14)

      Caused by: java.lang.ClassNotFoundException: javax.transaction.TransactionManager

      at java.net.URLClassLoader$1.run(Unknown Source)

      at java.net.URLClassLoader$1.run(Unknown Source)

      at java.security.AccessController.doPrivileged(Native Method)

      at java.net.URLClassLoader.findClass(Unknown Source)

      at java.lang.ClassLoader.loadClass(Unknown Source)

      at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)

      at java.lang.ClassLoader.loadClass(Unknown Source)

      … 23 more

      Reply
  47. Good day,

    I am a newbie in spring, hibernate and maven 🙂

    I saved “Spring-Hibernate-Annotation-Example.zip” extracted if afterwards and then imported it into eclipse…

    now, I am having problems since I do not have any of the libraries that has M2_REPO

    when I check my “.m2/repository” I cannot see any jar file in it.

    how can I get all the needed jar for this example? hope somebody can help me ^_^

    Reply
      1. Thanks for the fast reply sir ^_^

        I was able to set M2_REPO in my eclipse now.

        Sorry for being a complete noob on maven, spring & hibernate (my background is only struts 1, ant)

        How to I run this? 🙂

        Below are the things I tried:

        * mvn compile (SUCCESSFUL)
        * mvn test (SUCCESSFUL)
        * mvn install (SUCCESSFUL)
        * mvn deploy (ERROR)

        I am having this error 🙁

        [INFO] ————————————————————————
        [ERROR] BUILD ERROR
        [INFO] ————————————————————————
        [INFO] Failed to configure plugin parameters for: org.apache.maven.plugins:maven-deploy-plugin:2.4

        check that the following section of the pom.xml is present and correct:

        repo
        Repository Name
        scp://host/path/to/repo

        repo
        Repository Name
        scp://host/path/to/repo

        Cause: Class ‘org.apache.maven.artifact.repository.ArtifactRepository’ cannot be instantiated
        [INFO] ————————————————————————
        [INFO] For more information, run Maven with the -e switch
        [INFO] ————————————————————————
        [INFO] Total time: 11 seconds
        [INFO] Finished at: Wed Dec 14 12:34:00 PHT 2011
        [INFO] Final Memory: 14M/166M
        [INFO] ————————————————————————

        What else do I need sir to run/test this?

        Thanks a lot and Godbless.

        More Power ^_^

        Reply
        1. When I tried running App.java in eclipse I got the error below:

          Caused by: java.lang.ClassNotFoundException: javax.persistence.Entity
          	at java.net.URLClassLoader$1.run(URLClassLoader.java:217)
          	at java.security.AccessController.doPrivileged(Native Method)
          	at java.net.URLClassLoader.findClass(URLClassLoader.java:205)
          	at java.lang.ClassLoader.loadClass(ClassLoader.java:321)
          	at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:294)
          	at java.lang.ClassLoader.loadClass(ClassLoader.java:266)
          	... 24 more
          
          
          Reply
          1. Thanks a lot sir 🙂

            Got it working now

  48. [ERROR] Failed to execute goal on project SpringExample: Could not resolve dependencies for project com.mkyong.common:SpringExample:jar:1.0-SNAPSHOT: Failed to collect dependencies for [junit:junit:jar:3.8.1 (test), org.springframework:spring:jar:2.5.6 (compile), cglib:cglib:jar:2.2 (compile), mysql:mysql-connector-java:jar:5.1.9 (compile), hibernate:hibernate3:jar:3.2.3.GA (compile), hibernate-annotations:hibernate-annotations:jar:3.3.0.GA (compile), hibernate-commons-annotations:hibernate-commons-annotations:jar:3.0.0.GA (compile), dom4j:dom4j:jar:1.6.1 (compile), commons-logging:commons-logging:jar:1.1.1 (compile), commons-collections:commons-collections:jar:3.2.1 (compile), antlr:antlr:jar:2.7.7 (compile)]: Failed to read artifact descriptor for hibernate:hibernate3:jar:3.2.3.GA: Could not transfer artifact hibernate:hibernate3:pom:3.2.3.GA from/to JBoss repositor
    y (http://repository.jboss.com/maven2/): Access denied to: http://repository.jbo
    ss.com/maven2/hibernate/hibernate3/3.2.3.GA/hibernate3-3.2.3.GA.pom -> [Help 1]
    [ERROR]

    I use maven 3.0.3
    I got this error, please help
    Thank in advance

    Reply
  49. Hi Mkyong,

    Thank you for the great tutorial. Your blog is in my top training list. I have a small request:
    Could you rewrite and post an updated “pom.xml”-file?

    I read in JBoss’s blog that their repository “http://repository.jboss.com/maven2/” (which you use in the tutorial) is replaced with the new repository “https://repository.jboss.org/nexus/content/groups/”. So the current pom-file is not correct and the project does not run from the first attempt. I spent a lot of time until I find the correct dependencies. I hope that you will facilitate the other people if you update and rerun the project. Thank you in advance.

    Regards,
    Tsvetan

    Reply
    1. Thanks for your update, will review the related tutorials next month. Often times, technology is change too fast …

      Reply
  50. Hi

    I have completed the tutorial I have rewritten the pom file.
    I also downloaded mysql-5.5.16-win32.msi and mysql-workbench-gpl-5.2.35-win32.

    pom.xml

    4.0.0
    com.mkyong.common
    SpringExample
    jar
    1.0-SNAPSHOT
    SpringExample
    http://maven.apache.org

    junit
    junit
    3.8.1
    test

    org.springframework
    spring
    2.5.6

    cglib
    cglib
    2.2

    mysql
    mysql-connector-java
    5.1.9


    <!– hibernate hibernate3
    3.2.3.GA –>

    hibernate
    hibernate-tools
    3.2.3.GA

    dom4j
    dom4j
    1.6.1

    commons-logging
    commons-logging
    1.1.1

    commons-collections
    commons-collections
    3.2.1

    antlr
    antlr
    2.7.7

    org.slf4j
    slf4j-log4j12
    1.6.2

    javassist
    javassist
    3.4.GA
    true

    org.hibernate
    hibernate-commons-annotations
    3.2.0.Final

    org.hibernate
    hibernate-core
    3.6.0.Final

    org.glassfish.extras
    javaee
    3.1.1

    Reply
  51. Can you explain how to read datasource from tomcat server directory/external location instead of properties file

    thanks
    Krish

    Reply
  52. Hi again mkyong,

    I don’t quite get this method:

    @Autowired
    public void anyMethodName(SessionFactory sessionFactory)
    {
    setSessionFactory(sessionFactory);
    }

    Is it being called by someone or there’s no need? Also, the @Autowired is used to locate the SessionFactory Bean on Hibernate.xml right?

    Thanks in advance.

    Reply
    1. The reason I’m asking this is because I want to use multiple databases and thus multiple session factories (or at leaest thats my guess so far).
      Im guessing this method is being called by some delegate in some internal process but… What if I want to set a different session factory?

      Cheers!

      Reply
  53. Hi, I’m new to Java world and Spring and Maven and Netbeans! (I’ve always been a Visual Studio programmer) and this is an excelent tutorial to get hooked up.

    BUT… I’m trying to do a MVC Desktop Application, Model and Controller seem to work fine, but I’m having a hard time to get the data from the Controller to the View.

    How can I use the Model and the Controller on the View with spring?, I have noticed that web apps use the dwr.xml to use Controller methods.

    Thanks in advance!

    Reply
    1. I guess what im really asking is…

      How to configurate spring beans configuration files to use thru different projects? In my particular case, how can I use classes from Model and Controller projects in the View project.

      Or is it correct to instance a class the classic way?
      Class obj = new Class();

      Reply
        1. Thanks for responding…

          And finally, I’ve found the solution and it’s quite simple. When you have different projects (Model, Controller, Desktop View)you have to move the file “BeanLocations.xml” to the project who is going to use those Beans…

          In my case i had to move “BeanLocations.xml” from Controller to Desktop View project, and leave the Spring DB Configruation on the Controller.

          I hope it make some sense, I’m new to Java world.
          Excelent Tutorial BTW!

          Reply
  54. Hi,
    I am getting following error for each downloaded example. Am I missing any configuration?

    org.apache.maven.archetype.old.ArchetypeTemplateProcessingException: 
            Unable to add module to the current project as it is not of packaging type 'pom'
           //...
    [INFO] ------------------------------------------------------------------------
    [INFO] BUILD FAILURE
    [INFO] ------------------------------------------------------------------------
    [INFO] Total time: 1:14:52.281s
    [INFO] Finished at: Mon Jul 25 16:13:55 GMT+05:30 2011
    [INFO] Final Memory: 6M/15M
    [INFO] ------------------------------------------------------------------------
    [ERROR] Failed to execute goal org.apache.maven.plugins:maven-archetype-plugin:2
    .0:generate (default-cli) on project SpringExample: Unable to add module to the
    current project as it is not of packaging type 'pom' -> [Help 1]
    [ERROR]
    [ERROR] To see the full stack trace of the errors, re-run Maven with the -e swit
    ch.
    [ERROR] Re-run Maven using the -X switch to enable full debug logging.
    [ERROR]
    [ERROR] For more information about the errors and possible solutions, please rea
    d the following articles:
    [ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException
    
    Reply
    1. How you build this project? Normally, “mvn eclipse:eclipse =Dwtpversion=2.0” will do the best.

      Reply
      1. Please help me! Im trying to use maven + hibernate + spring since last week and i only got error. Now i’m trying to use your tutorial. When i use mvn archetype:generate, i get this error:

        [ERROR] BUILD FAILURE
        [INFO] ------------------------------------------------------------------------
        [INFO] : org.apache.maven.archetype.old.ArchetypeTemplateProcessingException: Unable to add module to the current project as it is not of packaging type 'pom'
        Unable to add module to the current project as it is not of packaging type 'pom'
        [INFO] ------------------------------------------------------------------------
        [INFO] For more information, run Maven with the -e switch
        [INFO] ------------------------------------------------------------------------
        [INFO] Total time: 1 minute 3 seconds
        [INFO] Finished at: Mon Aug 01 11:43:59 BRT 2011
        [INFO] Final Memory: 13M/127M
        [INFO] ------------------------------------------------------------------------
        

        If i use mvn eclipse:eclipse =Dwtpversion=2.0, i have this error:

        [INFO] Scanning for projects...
        [INFO] Searching repository for plugin with prefix: 'eclipse'.
        [INFO] ------------------------------------------------------------------------
        [ERROR] BUILD FAILURE
        [INFO] ------------------------------------------------------------------------
        [INFO] Invalid task '=Dwtpversion=2.0': you must specify a valid lifecycle phase, or a goal in the format plugin:goal or pluginGroupId:pluginArtifactId:pluginVersion:goal
        [INFO] ------------------------------------------------------------------------
        [INFO] For more information, run Maven with the -e switch
        [INFO] ------------------------------------------------------------------------
        [INFO] Total time: < 1 second
        [INFO] Finished at: Mon Aug 01 11:46:01 BRT 2011
        [INFO] Final Memory: 3M/44M
        [INFO] ------------------------------------------------------------------------
        
        Reply
          1. i’ve updated to maven 3.0.3 but mvn archetype:generate still failures. but mvn eclipse:eclipse works.

  55. BUILD FAILURE
    ---
    Failed to read artifact descriptor for hibernate:hibernate3:jar:3.2.3.GA: Could not transfer artifact hibernate:hibernate3:pom:3.2.3.GA 
    from/to JBoss repository (http://repository.jboss.com/maven2/): 
    Access denied to: http://repository.jboss.com/maven2/hibernate/hibernate3/3.2.3.GA/hibernate3-3.2.3.GA.pom -> [Help 1]
    
    Reply
    1. Access denied, bro.

      JBoss public repository is changed to “https://repository.jboss.org/nexus/content/groups/public-jboss/”

      Reply
  56. I need one full project in spring with code and netbean supported +mysql database

    Pls help me any body

    Reply
  57. Your tutorial saved my day!
    Simple, clear, very helpful.
    Applied on my NetBeans’ Swing + Spring 3 + Hibernate + postgresql

    Many thanks for sharing!

    Reply
  58. I want to use HSQL database and I changed the database:properties file.
    jdbc.driverClassName=org.hsqldb.jdbcDriver
    jdbc.url=jdbc:hsqldb:hsql://localhost:8080
    jdbc.username=sa
    jdbc.password=

    But I am taking this message

    Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in class path resource [spring/config/../database/Hibernate.xml]: Cannot resolve reference to bean 'dataSource' while setting bean property 'dataSource'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'dataSource' is defined
    Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'dataSource' is defined
    	at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:356)
    	at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedBeanDefinition(AbstractBeanFactory.java:916)
    	at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:243)
    	at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:160)
    	at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:261)
    	at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:109)
    	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1099)
    	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:861)
    	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:421)
    	at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:251)
    	at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:156)
    	at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:248)
    	at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:160)
    	at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:284)
    	at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:352)
    	at org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:91)
    	at org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:75)
    	at org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:65)
    	at com.mkyong.common.App.main(App.java:14)
    

    Could you HELP me? thanks a lot…

    Reply
  59. Hi,

    I couldnt solve the following issue 🙁 and need help please advise to get rid of this error.

    My POM file includes also following dependencies.

    javax.persistence
    persistence-api
    1.0

    javax
    javaee-api
    6.0

    ************************************************************************************
    Summary of error:

    Unexpected exception parsing XML document from class path resource [spring/config/BeanLocations.xml]; nested exception is java.lang.ClassFormatError: Absent Code attribute in method that is not native or abstract in class file javax/persistence/GenerationType
    ************************************************************************************

    Full stack trace:

    Connected to the target VM, address: '127.0.0.1:55489', transport: 'socket'
    document from class path resource [spring/config/BeanLocations.xml]; nested exception is 
    java.lang.ClassFormatError: Absent Code attribute in method that is not native or 
    abstract in class file javax/persistence/GenerationType
    

    Thank you for quick response.

    Reply
  60. Hi,

    I tried this example with JSF, but the ‘stockBo’ is still NULL. What is wrong ?
    Thanks.

    @Component
    @ManagedBean
    @SessionScoped
    public class StockBean {

    @Autowired
    private StockBo stockBo;
    private Stock stock;

    public void setStockBo(StockBo stockBo) {
    this.stockBo= stockBo;
    }

    public void save() {
    stockBo.save(stock);
    }

    …..

    }

    Reply
  61. Great Tutorial… but when i run it i have this error:

    Exception in thread “main” java.lang.NoClassDefFoundError: Ljavax/transaction/TransactionManager;

    Can you help me??

    Thanks a lot

    Flavio

    Reply
  62. I´ve installed java_ee_sdk-6u1-windows.exe but I couldn’t find javaee.jar

    where could I download this file?

    Reply
    1. It should be inside “JAVAEE_FOLDER\SDK\lib\javaee.jar” , for example “C:\Sun\SDK\lib\javaee.jar”

      Reply
  63. I put a new dependency at pom.xml

    javax.persistence
    persistence-api
    1.0

    Reply
  64. I get the following error: class path resource [spring/config/BeanLocations.xml] cannot be opened because it does not exist

    and all i have done is to import the entire project (with the classpath file) into Eclipse. What am i doing wrong?

    Reply
  65. You can very well use @Autowire for the HibernateDaoSupport. Not on the setter though (it’s final) but you can use @Autowire on the constructor.

    Reply
  66. ApplicationContext appContext =
    new ClassPathXmlApplicationContext(“config/BeanLocations.xml”);

    could you put some light on this statement?

    Thanks

    Reply
    1. Load the XML file and parse the content, if found any beans in the xml file, just load it into the Spring container.

      Reply
  67. Hi,

    In the example, to insert a “Stock” object you create the instance just like below;

    /** insert **/
    Stock stock = new Stock();

    But, isn’t it better to declare the Stock class as Spring component with the annatotion “@Component” and make the “Stock stock” decleration as @Autowired and use it like mentioned??

    What is the differences or adv./disadv. between those usage??

    Thanks…

    Reply
      1. Thank you very much for your reply :D. I like your posts, they really helps me. Do you think to post a tuto about gwt+spring integration :D, I am trying to do it and have some problems, it would help me.

        Reply
          1. When can we expect this tutorial?
            GWT + Hibernate; Can’t wait!
            Great job!

          2. Thanks Mkyong, I wonder if you provided a lesson for GWT + Spring + Hibernate + MySql. Since I have some issues for it as well, and I’ve never found a useful tutorial.

            Thanks
            Bahador Biglari

  68. Exception in thread “main” org.springframework.beans.factory.BeanDefinitionStoreException: Unexpected exception parsing XML document from class path resource [spring/config/BeanLocations.xml]; nested exception is java.lang.ClassFormatError: Absent Code attribute in method that is not native or abstract in class file javax/persistence/GenerationType

    Reply
    1. You should use javaee.jar from sun-library, because the other javaees don’t have all
      necessary classes (you can compile but during run you get errors).
      you can write for dependency so:

      javax
      javaee
      1.5.0
      system
      C:/SUN/SDK/lib/javaee.jar

      I think so you can run the app.
      best
      Parviz

      Reply
  69. Hi, I’ve been looking for the explanation between @Service @Repository,
    and often I end up with saying HQL/SQL are done in @Repository (DAO)
    and @Service will inject with multiple dao (repository)

    do you have any example on multiple dao in @Service?
    because it would give better view on how to apply multiple dao in @Service (eg. joining multiple tables, do we do this in @Service or @Repository?)

    *confused*

    Thanks in advance

    Reply
      1. Hi
        I do understand both @Service & @Repository are @Component
        but what I would like to see, is the application of @Service & @Repository from the DDD point-of-view (involving more than 1 dao, which this is what I couldn’t find on the internet)

        Thanks 🙂

        Reply
        1. Just declare the @Repository to any dao layers; @Service to business layers, it’s for convention and good practice, why you want to find an application to demo of it?

          Reply
  70. And I found this log message together . Could you help me please 🙁

    Caused by: java.lang.ClassNotFoundException: javax.transaction.TransactionManager
    	at java.net.URLClassLoader$1.run(Unknown Source)
    	at java.security.AccessController.doPrivileged(Native Method)
    	at java.net.URLClassLoader.findClass(Unknown Source)
    	at java.lang.ClassLoader.loadClass(Unknown Source)
    	at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    	at java.lang.ClassLoader.loadClass(Unknown Source)
    	... 23 more
    
    Reply
      1. Actually, this didn’t work for me….I ended up using:

        org.apache.openejb
        javaee-api
        5.0-2
        jar
        provided

        Reply
        1. Since you didn’t mention what “didn’t work” for you, so i can’t make any comments on it, this example is tested and worked well in my development environment. However, thanks for sharing your extra information 🙂

          Reply
  71. Hi,

    thank you for your tuto.

    But i’ve got an error when trying to compile App.java :

    INFO: Loading XML bean definitions from class path resource [spring/config/BeanLocations.xml]
    Exception in thread “main” org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path resource [spring/config/BeanLocations.xml]; nested exception is java.io.FileNotFoundException: class path resource [spring/config/BeanLocations.xml] cannot be opened because it does not exist

    I tryed but I can’t figure it out.

    Can you help me?

    Reply
    1. Look like the resource path error, did you compile it with Maven build before run? e.g, mvn eclipse:eclipse

      Reply
      1. Hi,

        Thank you for your response.

        No, I’ve build it like a java application directly in eclipse.

        I’ll try something else.

        Chesko

        Reply
        1. The attached is a maven, eclipse project, use Maven to build, it will do everything for use.

          Reply
          1. Hi,

            thank you .

            Tell me.
            what should I do if I want to use spring 3 ?
            I guess that I have to change JRE in build Path to 1.5 or higher?

            And Is it a good thing to use spring 3 ?

            Regards

Leave a Comment

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