This example will 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.
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 , 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>
<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 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
A Stock model class to store the stock data later.
package com.mkyong.stock.model;
import java.io.Serializable;
public class Stock implements Serializable {
private static final long serialVersionUID = 1L;
private Long stockId;
private String stockCode;
private String stockName;
//getter and setter methods...
}
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);
}
package com.mkyong.stock.bo.impl;
import com.mkyong.stock.bo.StockBo;
import com.mkyong.stock.dao.StockDao;
import com.mkyong.stock.model.Stock;
public class StockBoImpl implements StockBo{
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, the dao implementation class extends the Spring’s “HibernateDaoSupport” to make Hibernate support in Spring framework. Now, you can execute the Hibernate function via getHibernateTemplate().
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.stock.dao.impl;
import java.util.List;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import com.mkyong.stock.dao.StockDao;
import com.mkyong.stock.model.Stock;
public class StockDaoImpl extends HibernateDaoSupport 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.
Hibernate Configuration
Create a Hibernate mapping file (Stock.hbm.xml) for Stock table, put it under “resources/hibernate/” folder.
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.mkyong.stock.model.Stock" table="stock" catalog="mkyong">
<id name="stockId" type="java.lang.Long">
<column name="STOCK_ID" />
<generator class="identity" />
</id>
<property name="stockCode" type="string">
<column name="STOCK_CODE" length="10" not-null="true" unique="true" />
</property>
<property name="stockName" type="string">
<column name="STOCK_NAME" length="20" not-null="true" unique="true" />
</property>
</class>
</hibernate-mapping>
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. This LocalSessionFactoryBean class will set up a shared Hibernate SessionFactory in a Spring application context.
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.LocalSessionFactoryBean">
<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="mappingResources">
<list>
<value>/hibernate/Stock.hbm.xml</value>
</list>
</property>
</bean>
</beans>
Spring beans related….
Create a bean configuration file (Stock.xml) for BO and DAO classes, put it into the “resources/spring” folder. Dependency inject the dao (stockDao) bean into the bo (stockBo) bean; sessionFactory bean into the stockDao.
Stock.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">
<!-- Stock business object -->
<bean id="stockBo" class="com.mkyong.stock.bo.impl.StockBoImpl" >
<property name="stockDao" ref="stockDao" />
</bean>
<!-- Stock Data Access Object -->
<bean id="stockDao" class="com.mkyong.stock.dao.impl.StockDaoImpl" >
<property name="sessionFactory" ref="sessionFactory"></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
<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">
<!-- Database Configuration -->
<import resource="../database/DataSource.xml"/>
<import resource="../database/Hibernate.xml"/>
<!-- Beans Declaration -->
<import resource="../beans/Stock.xml"/>
</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
how to select all rows from the database?
if I do StockDaoImpl stockDao;
and Inject the StockDaoImpl. Then what will go wrong?
I am facing 1 issue where I am taking reference variable of Impl class type like StockDaoImpl and its giveing me No conversion mechanism provide for converting ‘Proxt$68 imlementing XXXX, YYY, XXXProxy….’ to ‘Proxt$68 imlementing XXXX, YYY, XXXProxy….’
Please let me know what goes wrong?
[ERROR] Failed to execute goal on project SpringExample: Could not resolve dependencies for project com.mkyong.common:SpringExample:jar:1.0: Failure to find org.hibernate:hibernate:jar:3.2.3.ga in http://repo.maven.apache.org/maven2 was cached in the local repository, resolution will not be reattempted until the update interval of central has elapsed or updates are forced -> [Help 1]
Same error.
in your project directory every xml file in different folder not in resource]
tks :V
Can’t we use a single xml file for the bean instead of 4 as in the above example>
HibernateDaoSupport is not present in Hibernate dependency you provide it throws an error needed javax-transaction jar
could you please suggest any changes in the pom.xml
After searching I replaced hibernate dependency with spring-orm and I have still problems
Caused by: java.lang.ClassNotFoundException: org.hibernate.cfg.Configuration
change dependency to
org.hibernate
hibernate
3.2.3.ga
then clean and re install the project if ur using eclipse or netbeans
it may help ..
Doesn’t work. Even if I copy paste. WTF?
Hi
how can i implement two controller means one maincontroller and restcontroller in spring mvc maven
Exception in thread “main” org.springframework.dao.InvalidDataAccessResourceUsageException: Cannot open connection; SQL [???]; nested exception is org.hibernate.exception.SQLGrammarException: Cannot open connection
HI, I used these file structure and almost everything as the same for my project. The only difference I have in my project is I use Spring Boot. When I run the project, it gives me following error.
*********************************************************************************************************************************************
Parameter 0 of constructor in org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration required a bean of type ‘javax.sql.DataSource’ that could not be found.
– Bean method ‘dataSource’ not loaded because @ConditionalOnProperty (spring.datasource.jndi-name) did not find property ‘jndi-name’
– Bean method ‘dataSource’ not loaded because @ConditionalOnBean (types: org.springframework.boot.jta.XADataSourceWrapper; SearchStrategy: all) did not find any beans
*********************************************************************************************************************************************
My question is, what am I missing. Doesn’t spring boot support the file structure and the configuration shown here? How can I fix the issue?
Hi, Mr. Yong,
Thanks for this tutorial.
I’m using Hibernate for SAP HANA database. I’m able to persistent data using preparedStatements but I’m getting problem with using hibernate. Please tell me what changes are required in this example so that I can integrate sap hana and hibernate.
Hi Nice one, i follow the step and run the program,however lots of maven issue were there after all sort it out, it succedd.
Please add same example with annotation based injection instead of xml based.
CLEAR PRESENTATION:
public class App
{
public static void main( String[] args )
{
ApplicationContext appContext = new ClassPathXmlApplicationContext(“springconfig/BeanLocations.xml”);
StockBo stockBo = (StockBo)appContext.getBean(“stockBo”);
/** insert **/
Stock stock = new Stock(7,”73″,”Yunus”);
stockBo.save(stock);
System.out.println(“INSERT: “+stock);
/** select **/
Stock stock2 = stockBo.findByStockCode(“73”);
System.out.println(“READ: “+stock2);
/** update **/
stock2.setStockName(“HAIO”);
stockBo.update(stock2);
System.out.println(“UPDATE: “+stock2);
/** delete **/
stockBo.delete(stock2);
Mr. Yong,
I need a inner join. What should I do with my HQL? should i create a new model class with the HQL or put the HQL in one of the classes i want to join? What is the proper way to do it?
I’m stuck in this, because i want to work with it correctly. I need to retrive some information from different tables
Hii… I want to use named query instead of normal HQL in the above example. Can you please throw some light on that….
Hi…i am getting error when trying add dependency of MySql. iam using MySql 5.1.73
error:Missing artifact mysql:mysql-connector-java:jar:5.1.7
please help me
Great tutorial to start with Spring and hibernate together 🙂
Nice tutorial! There’s a great RAD tool out called Jigy Generator that automatically spits you out a fully configured spring project which can already connect to your database, authenticate users, handle file uploads, etc. It even creates dao’s, domain objects and validators in your project by reverse engineering your database. This way you don’t have to get mired in the low level details of spring and hibernate… It Just Works! You can download the project at http://www.getjigy.com
Thanks you so much, really helpful, I have to update pom.xml and it run perfect.
So old and not working
Thanks a lot mkyong. This article is very helpful. I used these steps and tried to build my project and it worked like a charm. Also my project looked more organized.
Good tutorial, with some minnor mistakes, but a great resource of knowledge.
This tutorial isn’t worth to try. If you follow the instructions he gives, your app won’t run. Wrong directories, wrong files path. Thank you for wasting my time following your howto.
i am getting this error..can u plz help me
Error: Could not find or load main class com.login.common.App
problem with your package …
Good Job Man 🙂
Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1.2.1:exec (default-cli) on project SpringExample: Command execution failed. Process exited with an error: 1 (Exit value: 1) -> [Help 1]
Pls help me in fixing this pblm. Thanks
Hi, Mkyong,HibernateDaoSupport is not recommend,because this unnecessarily ties code to spring classes which means I have to use older version of Hibernate.So, there is no HibernateDaoSupport in package org.springframework.orm.hibernate4.
hi Mkyong, this example is very helpful for me. thanks so much
hi Mkyong ,your tutorial on spring+hibernate with “CRUD” operation is good but if we want to work with bulk operations using hibernate like we were used to do in hibernate using hibernate methods and classess ,How can we perform in spring+hibernate scenerio ? please explain.
the example is perfect and good example for those who want to setup spring hibernate quickly. there is one fix. Just replace maven dependency of hibernate3.2.3 GA with
org.hibernate
hibernate
3.2.3.ga
all the best cheer 🙂
* plus + the following dependency
javax.transaction
jta
1.1
Indeed. This dependency is missing inside pom.xml file of the example.
Also we need to modify .classpath file under path where you having this unziped source code like as follows :
I got this error when running App.java :–
Oct 3, 2013 10:56:26 AM org.springframework.beans.factory.support.DefaultSingletonBeanRegistry destroySingletons
INFO: Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@13c1b02: defining beans [org.springframework.beans.factory.config.PropertyPlaceholderConfigurer#0,dataSource,sessionFactory,stockBo,stockDao]; root of factory hierarchy
Exception in thread “main” org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘sessionFactory’ defined in class path resource [spring/database/Hibernate.xml]: Initialization of bean failed; nested exception is java.lang.NoClassDefFoundError: javax/transaction/TransactionManager
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:480)
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)
whe i am running in the eclipse it is showing Error exists in required project..can any one can help
Its really great article and as usual Mkyong style…great approach to develop any code base.
I got maven error like this :
Failed to execute goal on project SpringExample: Could not resolve dependencies for project com.mkyong.common:SpringExample:jar:1.0-SNAPSHOT: Failure to find hibernate:hibernate3:jar:3.2.3.GA in http://repo.maven.apache.org/maven2 was cached in the local repository, resolution will not be reattempted until the update interval of central has elapsed or updates are forced -> [Help 1]
no mames cabron kp2
Hi ,
I tried to execute this example, It was not working in my machine due to small migration of artifact id from hibernate3 to hibernate and group id hibernate to hibernate org.hibernate and one interdependence for hibernate 3.2.7 jar i.e javax.transaction as showed below and Remote repo as
SOntatype RSA
SOntatype RSA
https://oss.sonatype.org/content/repositories/releases/
maven2
http://repo1.maven.org/maven2
org.hibernate
hibernate
3.2.7.ga
javax.transaction
jta
1.1
http://www.fileconvoy.com/dfl.php?id=g3dd6b0d0172a56609992865441cab3045564c9cba
http://www.fileconvoy.com/dfl.php?id=g2c5842d624f8f604999286545e67b178e02732f79
i changed some codes then it works properly……
1.add this to pom file
org.hibernate
hibernate-core
3.3.2.GA
org.slf4j
slf4j-log4j12
1.6.1
javassist
javassist
3.12.1.GA
2.add this in StockBoImpl
public StudentDAO getStockDao(StockDAO stockDAO) {
return stockDAO;
}
public void setStockDao(StockDao stockDao) {
this.stockDao = stockDao;
}
yep me 2
Thanks for your tip =)
Hello, I’ve seen following error most of the times. Could any one please help me to resolved this error?
“An internal error occurred during: “Updating Maven Project”.
Unsupported IClasspathEntry kind=4″
if you are just using spring+hibernate+eclipse+mysql your jars should be:
antlr-2.7.7.jar
commons-collections-3.2.1.jar
dom4j-1.6.1.jar
hibernate-3.2.3.ga.jar
spring-2.5.6.jar\spring-2.5.6.jar
commons-logging-1.1.1.jar
cglib-2.2.2.jar
asm-3.3.1.jar
jta-1.1.jar
mysql-connector-java-5.1.24.jar
Hi,
I’m getting this error when I run the app.
INFO: Building new Hibernate SessionFactory
24-Feb-2013 20:26:34 org.springframework.beans.factory.support.DefaultSingletonBeanRegistry destroySingletons
INFO: Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@11121f6: defining beans [org.springframework.beans.factory.config.PropertyPlaceholderConfigurer#0,dataSource,sessionFactory,stockBo,stockDao]; root of factory hierarchy
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.hibernate.HibernateException: Unable to instantiate default tuplizer [org.hibernate.tuple.entity.PojoEntityTuplizer]
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.hibernate.HibernateException: Unable to instantiate default tuplizer [org.hibernate.tuple.entity.PojoEntityTuplizer]
at org.hibernate.tuple.entity.EntityTuplizerFactory.constructTuplizer(EntityTuplizerFactory.java:108)
at org.hibernate.tuple.entity.EntityTuplizerFactory.constructDefaultTuplizer(EntityTuplizerFactory.java:133)
at org.hibernate.tuple.entity.EntityEntityModeToTuplizerMapping.(EntityEntityModeToTuplizerMapping.java:80)
at org.hibernate.tuple.entity.EntityMetamodel.(EntityMetamodel.java:322)
at org.hibernate.persister.entity.AbstractEntityPersister.(AbstractEntityPersister.java:485)
at org.hibernate.persister.entity.SingleTableEntityPersister.(SingleTableEntityPersister.java:133)
at org.hibernate.persister.PersisterFactory.createClassPersister(PersisterFactory.java:84)
at org.hibernate.impl.SessionFactoryImpl.(SessionFactoryImpl.java:286)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1845)
at org.springframework.orm.hibernate3.LocalSessionFactoryBean.newSessionFactory(LocalSessionFactoryBean.java:814)
at org.springframework.orm.hibernate3.LocalSessionFactoryBean.buildSessionFactory(LocalSessionFactoryBean.java:732)
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.reflect.InvocationTargetException
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 org.hibernate.tuple.entity.EntityTuplizerFactory.constructTuplizer(EntityTuplizerFactory.java:105)
… 28 more
Caused by: java.lang.NoClassDefFoundError: javassist/util/proxy/MethodFilter
at org.hibernate.bytecode.javassist.BytecodeProviderImpl.getProxyFactoryFactory(BytecodeProviderImpl.java:49)
at org.hibernate.tuple.entity.PojoEntityTuplizer.buildProxyFactoryInternal(PojoEntityTuplizer.java:205)
at org.hibernate.tuple.entity.PojoEntityTuplizer.buildProxyFactory(PojoEntityTuplizer.java:183)
at org.hibernate.tuple.entity.AbstractEntityTuplizer.(AbstractEntityTuplizer.java:167)
at org.hibernate.tuple.entity.PojoEntityTuplizer.(PojoEntityTuplizer.java:77)
… 33 more
Caused by: java.lang.ClassNotFoundException: javassist.util.proxy.MethodFilter
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)
… 38 more
These tutorials are pretty old and getting quite useless…how about hibernate 4, HibernateDaoSupport is not even recommended for long time now…before following these article you should look for date on it…these article are OUTDATED…
You are right Ben, here’s one Spring 3 and Hibernate 4 example http://www.cavalr.com/blog/Spring_3_and_Hibernate_4_Example.
Hope it works for you.
You should change the protostuff version the archetype pom.xml to 1.0.7 to make it work with the mvn eclipse:eclipse command.
Great article! It’d be good if you updated it to use annotations instead of hibernate xml mapping. If someone follows this article, he’ll need to modify quite many things.
Anyway, thanks!
hi, im working on this tutorial, it’s very helpfull but i have somme errors, like :
Class ‘org.apache.commons.dbcp.BasicDataSource’ not found
Class ‘org.springframework.orm.hibernate3.LocalSessionFactoryBean’ not found
HibernateDaoSupport cannot be resolved to a type > StockDaoImpl.java
and i can’t find any solution, would you like to help me please ?
Hello Mr. Yong,
Nice tutorial you’ve posted. I followed step-by-step – just got stuck in the end.
You mentioned :
————–
Import all the Spring’s beans configuration files into a single file (BeanLocations.xml), put it into the “resources/config” folder.
BeanLocations.xml
… …
Then in App.java
——————
main() method {
ApplicationContext appContext =
new ClassPathXmlApplicationContext(“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
Caused by: java.io.FileNotFoundException: class path resource [spring/config/BeanLocations.xml] cannot be opened because it does not exist
at org.springframework.core.io.ClassPathResource.getInputStream(ClassPathResource.java:143)
———–
I am getting above Error because of this incorrect path. tried changing to “config/…” , “/config/…” , “resources/config/…” , but all didn’t work.
Project ‘clean’ and Rebuild many times. Didn’t help much.
Also ‘target’ folder has ‘classes/resources’ – then all empty folders created for all resources needed in application. Not able to get all XML files copied under target dir.
Why would you mention “spring” in the appContext path ??
Does ‘config’ come under ‘resources/spring’ ??
Would appreciate your valuable help in resolving this. please help asap !!
Thanks, Harpreet
On Eclipse, try to shift click on resources folder => Build Path => Use as source folder.
Hi,
Thanks for this very helpful example.
Should the line:
actually be:
Thanks,
Nana
Oops! Here is the line in the BeanLocations.xml file that I thought need to be corrected to:
Instead of…
An example on Maven + Spring MVC + Hibernate + MySQL.
That would help a lot, thanks.
Can someone pls post one example in Netbeans + Hibernate + Spring?
Hello.
I am getting the following error when trying to import the exercise file:
An internal error occurred during: “Updating Maven Project”.
Unsupported IClasspathEntry kind=4
Can anyone help me?
Group id of hibernate dependency should be “org.hibernate”. NOT just “hibernate”
here is the correct entry….
<dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate</artifactId> <version>3.2.3.ga</version> </dependency>Thank you for you tips.
Thanks. This works for me.
@Charly please did you add any changes in this code because I have exception in sessionFactory Bean , thank you .
org.springframework.beans.factory.BeanCreationException: Error creating bean with name
Hi I getting the following error and unable to resolve it plz help me…………
‘sessionFactory’ defined in class path resource [com/barun/blog/resources/spring/databases/Hibernate.xml]: Invocation of init method failed; nested exception is java.lang.NoSuchFieldError: sqlResultSetMappings
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1403)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:450)
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:290)
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:287)
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:189)
org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:545)
org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:871)
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:423)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:443)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:459)
org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:340)
org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:307)
org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:127)
javax.servlet.GenericServlet.init(GenericServlet.java:212)
org.apache.jasper.runtime.PageContextImpl.doForward(PageContextImpl.java:709)
I have the following error when building with maven.
Hi,could you tell us which Maven archetype because If I try use option 15 as you did I get a maven-archetype-executable archetype.
Your help is greatly appreciated
Thanks for your concise and self-explanatory tutorial! I have one small question regarding to the application design in this tutorial.
I was wondering what is the purpose of having an extra BO abstraction on top of the DAO abstraction.
Isn’t the StockDao interface already provides a good abstraction to hide the actual database operation works, which are implemented in StockDaoImpl, from the application layer?
Thanks!
Normally, Bo is for business logic, Dao is for database layer only. You can mixed both Bo and Dao together, but maintenance is hard.
Great Tutor. Thanks a million.
Hello mkyong.
Great Example. You are superb. Explained in very simple way. Very nice. Thanks a ton Guru.
I am getting this error..any help please…
Exception in thread “main” org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘sessionFactory’ defined in class path resource [spring/database/Hibernate.xml]: Initialization of bean failed; nested exception is java.lang.StackOverflowError
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:527)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
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:563)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:913)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:464)
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.StackOverflowError
Dear Bala
run the following command on the command prompt
mvn eclipse:eclipse -Dwtpversion=1.5
By Anand singh, Napgur
Hi, which Maven archetype should I use to get a project structure like the one on the first image?
simply great
Hi Mkyonk,
Thanks for uploading the nice tutorial,
Can you please also explain me, how to generate .war file and including the JSPs in the same application.
It will be great help to me in my recent assignment..
Hi Mkyong,
thank you for all your tutorials, they inspire me,
I want to ask you, i use HibernateDaoSupport to create my Dao, and i have a many to one relation, whene itry to get the child object i have a LazyInitializationException.
i searched everywhere and i didn’t find the right solution for me.
thanks for your help
Hi,
Thanks to post such a Nice example step by step. I tried to run in my local. but i got below exception . Please help me to resolve this exception.
Hibernate annotation jar is missing? Did you include it?
Thanks For reply. I resolved problem by the help of Google.
Hi,
I am getting following error while Maven->Build option
[ERROR] Failed to execute goal on project SpringExample: Could not resolve dependencies for project com.mkyong.common:SpringExample:jar:1.0-SNAPSHOT: Failure to find javax.transaction:jta:jar:1.0.1B in http://repo.maven.apache.org/maven2 was cached in the local repository, resolution will not be reattempted until the update interval of central has elapsed or updates are forced -> [Help 1]
Please help me..
You might change the following in your pom from:
to:
Hi,
Mkyoung.
your all post is Excellent.
Thanks for this valuable content posting.
Regards,
Krunal
can someone please publish the pom.xml that can work? I am getting many NoClassFound exceptions. I use 1.6 version of java. regards.
Superb!!!! Brillant tutorila ..so easy to understand …kudos to mykong for helping us
[INFO] BUILD FAILURE
[INFO] ————————————————————————
[INFO] Total time: 2:03.485s
[INFO] Finished at: Tue Jul 24 11:31:16 ICT 2012
[INFO] Final Memory: 3M/7M
[INFO] ————————————————————————
[ERROR] Failed to execute goal on project SpringExample: Could not resolve dependencies for project com.mkyong.common:SpringExample:jar:1.0-SNAPSHOT: Could not find artifact hibernate:hibernate3:jar:3.2.3.GA in central (http://repo.maven.apache.org/maven2) -> [Help 1]
<!-- Hibernate framework --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>4.0.0.Final</version> </dependency>I have the same problem, how to solve it???
I am also getting same error message
Failed to execute goal on project SpringExample: Could not resolve dependencies for project com.mkyong.common:SpringExample:jar:1.0-SNAPSHOT: Could not find artifact org.hibernate:hibernate3:jar:3.2.3.GA in central (http://repo.maven.apache.org/maven2) -> [Help 1]
To see the full stack trace of the errors, re-run Maven with the -e switch.
Re-run Maven using the -X switch to enable full debug logging.
How to solve it?
Regards
Hello MkYong, greetings to you. You contribute so much to the open source community, a true legend in my view. Amazing how u can explain advanced topics in a very simple way. Unbelievable.
Thanks for your kind words, I just try to keep it in particle n as simple as possible.
Really Thanks a lot for helping every one ….. God bless you
clear and very helpful,
thank u very much
Hello Mkyong,
Very fruitful tutorial. Thanks for uploading these tutorials!!!!!!!!!!!
Good Job!!!!!!
Is there a way to connect to remote session of hibernate?
For ex :- Instead of org.springframework.orm.hibernate3.LocalSessionFactoryBean
using org.springframework.orm.hibernate3.RemoteSessionFactoryBean
mkyong,
I am trying to follow this tutorial to get a similar system working on my machine. I am brand new to spring/hibernate but have suffcient java experience. I’m using spring version 3.1.1.RELEASE and hibernate version 4.1.1.FINAL. I believe I have made the necessary changes to this code to make it work but I am getting an error and cannot find a solution online anywhere so I thought I’d ask the expert. The error is:
SLF4J: slfjj-api 1.6.x(or later) is incompatible with this binding.
SLF4J: Your binding is version 1.5.5 or earlier (I’m using slf4j-log4j12 version 1.5.5)
SLF4j:Upgrade your binding to version 1.6.x or 2.0.x
Can you please tell me how to fix this or what changes I need to make to your code to get my versions to work!
Robi:
Here are the detailed steps to run this excellent project in Eclipse
There are some steps you need to perform before (Prepare the environment) running this in eclipse. They are:
1. Install mysql
2. Install maven
3. Download the zip file (https://mkyong.com/wp-content/uploads/2010/03/Spring-Hibernate-Example.zip)
4. Run “mvn clean install” (this will download the necessary/dependencies as outlined in pom.xml)
5. I ran into an error with jta.jar not being found in the repository. I added it manually thru maven
Steps for Eclipse setup:
————————
1. Steps outlined in the Preparation section
2. Extract it in your eclipse workspace directory
3. Open eclipse
4. Import this project into Eclipse (Import -> Java -> existing project)
5. Set a M2_REPO variable in eclipse and set it to the $HOME/.m2/repository
6. Now, everything in Eclipse should be set (no compile errors)
7. Right click on App.java and run as a java application
You should see the output in the console window
Hello mkyong, all your articles are so helpful to the rest of IT community. Thanks for contributing so much!
My query – you have used spring 2.5.6 using this dependency
<dependency> <groupId>org.springframework</groupId> <artifactId>spring</artifactId> <version>2.5.6</version> </dependency>I could see in the maven repo that spring version 3.1.1.RELEASE is also available (but that’s just for some individual spring modules such as spring-core and not for the artifact you have used i.e. spring). How can I use this version 3.1.1.RELEASE in my project? Will I have to add individual modules which are available at 3.1.1?
Since am a bigginer please let me know how to run the project in eclipse to see the exact output??
I’m developing a Shibboleth extension and need to integrate my extension with a MySQL database.
Does anybody know how I configure the hibernate in Shibboleth, and how do I code my extension in Java to get the data from de database?
I think that:
– what goes in BeanLocations.xml, I can put in internal.xml at Shibboleth;
– there might have a context ready to use in Shibboleth, so I don’t need to call ApplicationContext appContext = new ClassPathXmlApplicationContext(“spring/config/BeanLocations.xml”). But, how I get this context in Shibboleth?
Thanks for any help,
Eduardo
nice work, thank you.
my additional dependencies:
– spring-orm
– hibernate-core (not hibernate3)
– javassist
Hi mkyong
How can I used in this example configuration from spring security for authentication user role permission?
please help me.
i create my project with this pom.xml in example and can’t used spring security .
I am using hibernate by making use of xml files not annotations, I would like to populate the database from these same xml files,is this possible? or do I have to make use of other libraries.
To download hibernate dependencies ,We should change your Code MKYONG :
By this:
Thanks. It helped me.
Not At all
Hello, I think, you will be doing a great service if you provide the hands-on tutorials at three levels as follows.
1) without using IDE or build-tools like Ant or Maven.
( this is ideal. Afterall, all that we need is info about the jars in class path.
Bringing in IDE and such, merely confuses the picture.
11) using ANT or MAVEN
iii) using Eclipse.
—————————————————————–
Also, you must use very simple tables for illustration.
I would like to have your response about my suggestion.
I need a simple tutorial on integration of Hibernate3 and Spring2.
Command line program only without AND/MAVEN
Thanks.
Thanks for your suggestion. Yup, almost all tutorials are develop under Eclipse + Maven, become Maven is still the best way to demonstrate the use of dependency libraries.
For Jars in classpath, you can found the entire dependency library detail in Maven pom.xml. Maven is just added an extra pom.xml and follow the Java standard folder structure, you can convert to Ant, or using any IDE (Eclipse or Netbean) to develop Maven project.
1. To integrate Spring and Hibernate, refer above article.
2. To run it command line without ANT or Maven, a bit weird and not recommended, but you can do it, just make sure you set your class path correctly.
I think Maven is great. Definitely the way to roll. Great job on the tutorial!
sorry for this newbie question.
why do we need business object if we have dao?
why do we need the dao interface then create new class to implement it?
it seems too much for a simple transaction
thanks
Hey, everything is working fine, but there is some problem with persistence in database.
Hibernate shows that it is inserting and updating values(I commented out delete), but still there is no change in original mysql table.
Sorry got the solution, my bad
Mistake from my side.
Hi,
I have followed this tutorial but Spring is not injecting any of the dependencies.
What can I do to track this down?
Thanks
C
I am getting bean error when “SessionFacotry” bean is creating, it saying transaction argument is missing.. or something.
Sorry for not having stacktrace at this moment. Also let me know in the basic Hibernate mapping we will open session, from which we shall begin transaction..
How do we do when Hibernate is integrated with the Spring ?
In your pom.xml use, search for dependency with groupId-cglib and replace that with this:
cglib
cglib-nodep
2.2.2
REASON: http://www.hildeberto.com/2008/05/hibernate-and-jersey-conflict-on.html
Hi Mykong ,
I am getting an error in the creation of the sessionFactory bean, as a result all my beans like StockDAO and StockBO referred to this bean is giving me errors.
it is saying transaction/jdbc error.. not having the error stack trace at this moment..
Also in Hibernate programs inside the sessionFactory, once after opening the new session we will begin with the transaction.. and perform the operations..
Please let me know how we do when we integrate Spring with Hibernate ?
Hi Mkyong,
I tried this tutorial and getting the below error, Can you please help here…
I am using Hibernate 3.6.8 and spring 3.0.5 verions.
“The content of elements must consist of well-formed character data or markup.”.
Some errors in your XML file, please verify.
Hi mkyong,
short and good article to get started, i got it working pretty fast. I went a step ahead to use Hibernate Shards with the app. 2 DBs, PK for one with Auto-increment at 1 and other one at 1000
Modified your App class to do:
—————————————-
/** insert **/
for(int i = 0; i < 10 ; i++) {
Stock stock = new Stock();
stock.setStockCode(UUID.randomUUID().toString().substring(0, 8));
stock.setStockName(UUID.randomUUID().toString().substring(0, 8));
stockBo.save(stock);
System.out.println("Inserted: " + stock.getStockId());
}
————————————————–
Output shows:
Hibernate: insert into stock (STOCK_CODE, STOCK_NAME) values (?, ?)
Inserted: 20
Hibernate: insert into stock (STOCK_CODE, STOCK_NAME) values (?, ?)
Inserted: 1001
Hibernate: insert into stock (STOCK_CODE, STOCK_NAME) values (?, ?)
Inserted: 21
Hibernate: insert into stock (STOCK_CODE, STOCK_NAME) values (?, ?)
Inserted: 1002
Hibernate: insert into stock (STOCK_CODE, STOCK_NAME) values (?, ?)
Inserted: 22
Hibernate: insert into stock (STOCK_CODE, STOCK_NAME) values (?, ?)
Inserted: 1003
Hibernate: insert into stock (STOCK_CODE, STOCK_NAME) values (?, ?)
Inserted: 23
Hibernate: insert into stock (STOCK_CODE, STOCK_NAME) values (?, ?)
Inserted: 1004
Hibernate: insert into stock (STOCK_CODE, STOCK_NAME) values (?, ?)
Inserted: 24
Hibernate: insert into stock (STOCK_CODE, STOCK_NAME) values (?, ?)
Inserted: 1005
Done
==========================================================\
ISSUE is: The entries do not show up in database. If i run app again, it increment from the previous runs, so it knows the numbers, but the data is not committed to DB.
Any ideas? Thanks in advance.
My advice is download the project, try it and compare with yours.
Hi mkyong,
your project works fine but when I try to configure with another schema (which is readOnly) finding following stack trace and was trying for couple of days without any luck. Can you please suggest / pointer for fix for it ?
StackTrace:-
Exception in thread “main” org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘esiBo’ defined in class path resource [spring/beans/ExtractNimsInfo.xml]: Cannot resolve reference to bean ‘esiDAO’ while setting bean property ‘esiDAO’; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘esiDAO’ defined in class path resource [spring/beans/ExtractNimsInfo.xml]: Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property ‘NimsDataSource’ of bean class [com.allstream.aolng.initload.dao.impl.ExtractSeedInfoDAOImpl]: Bean property ‘NimsDataSource’ is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:328)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:106)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1305)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1067)
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.(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:83)
at com.mkyong.common.App.main(App.java:37)
what snippet of code I am missing with your code for readonly db.
Thanks in advance.
Saurabh
I think I am still having problems in step 2 – I thinks the issue is lack of details about WHAT to generate and ASSUMPTIONS about the maven versions running.
Step two says :
But I do not think MY option 15, is the same option 15 you used – and there is NO INFORMATION about what option 15 is in your setup. The file structure and POM file generated by MY option 15 is nothing like what I see in your example.
When I run the “mvn archetype:generate” command, I am presented with 518 options, and MY option 15 is “15: remote -> com.googlecode.apparat:apparat-archetype-tdsi (-)” which means absolutely nothing to me.
Is this the same option used in this example?
This tutorial is using Maven 2.x, are you using Maven 3?
Yes, I was using Maven Version 3.
In my previous post I explained that when I used Maven Version 2, it died when I executed the command “mvn eclipse:eclipse” with this error.
Since you will not tell me what maven archetype you are using to generate, and my #15 as in your example does not seam to generate the same structure that you got – either with maven 2 or maven 3. I have given up trying to get it running from scratch.
I downloaded your project then ran the maven command
“>mvn eclipse:eclipse -Dwtpversion=2.0” against it.
Maven failed to get the hibernate3-3.2.3.ga.jar file, but i was able to locate a “hibernate-3.2.3.ga.jar” which I manually downloaded. Note the slight file name difference: I found “…e-3.2…” NOT “…e3-3.2…”
(Even after I corrected the POM file entry
from “hibernate3”
to “hibernate”
Maven still failed to download it – I guess the information Maven is using is out of date?
I then had to change the project build path so it pointed at MY maven repository location.
Still, after all that the project still fails to run.
Now I am getting this error in my console output:
I am running into problems at step 2.
I got Maven installed ( which I have not used before ), and ran the generate command and used option 15, and everything appeared to work I think.
Then step 2 continues to say “Convert it to Eclipse project (mvn eclipse:eclipse) and import it into Eclipse IDE.”
So I navigated into the project directory, where the generated pom file was, and executed “mvn eclipse:eclipse”, but I am getting a error – being ignorant of Maven, I do not know how to fix it! My guess would be I needed Maven version 3.0-beta-1, but what is cauing it to need a beta version, instead of the last stable build , Maven 2.2.1 which is what I downloaded???
I don’t even see a Maven version 3.0-beta-1 available for download!
[ERROR] BUILD ERROR [INFO] ------------------------------------------------------------------------ [INFO] Error resolving version for 'org.sonatype.flexmojos:flexmojos-maven-plugin': Plugin requires Maven version 3.0-beta-1 [INFO] ------------------------------------------------------------------------ [INFO] Trace org.apache.maven.lifecycle.LifecycleExecutionException: Error resolving version for 'org.sonatype.flexmojos:flexmojos-maven-plugin': Plugin requires Maven version 3.0-beta-1 at org.apache.maven.lifecycle.DefaultLifecycleExecutor.verifyPlugin(DefaultLifecycleExecutor.java:1549) at org.apache.maven.lifecycle.DefaultLifecycleExecutor.getMojoDescriptor(DefaultLifecycleExecutor.java:1787) at org.apache.maven.lifecycle.DefaultLifecycleExecutor.segmentTaskListByAggregationNeeds(DefaultLifecycleExecutor.java:462) at org.apache.maven.lifecycle.DefaultLifecycleExecutor.execute(DefaultLifecycleExecutor.java:175) at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:328) .... Caused by: org.apache.maven.plugin.version.PluginVersionResolutionException: Error resolving version for 'org.sonatype.flexmojos:flexmojos-maven-plugin': Plugin requires Maven vers ion 3.0-beta-1 at org.apache.maven.plugin.DefaultPluginManager.checkRequiredMavenVersion(DefaultPluginManager.java:286) at org.apache.maven.plugin.DefaultPluginManager.verifyVersionedPlugin(DefaultPluginManager.java:205) at org.apache.maven.plugin.DefaultPluginManager.verifyPlugin(DefaultPluginManager.java:184) at org.apache.maven.plugin.DefaultPluginManager.loadPluginDescriptor(DefaultPluginManager.java:1642) at org.apache.maven.lifecycle.DefaultLifecycleExecutor.verifyPlugin(DefaultLifecycleExecutor.java:1540) ... 15 more [INFO] ------------------------------------------------------------------------When I repeated step 2 with apache-maven-3.0.3-bin.zip, everything worked OK.
Don’t get you.. may be you can try this – https://mkyong.com/misc/how-to-use-mkyong-tutorial/
Hello MKYong
I am also witnessed the quality of your work ….thank you very much
t get the following exception :
think you
Double check your “DataSource.xml”, make sure all XML tag are valid. Try download above project and compare it with yours.
Think you 🙂
Hello MKyong
I have anther probleme :(, i use maven3 and hiberate3 , it is related to slf4j-logger ?!
thank you.
16 déc. 2011 12:02:08 org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@d1e604: display name [org.springframework.context.support.ClassPathXmlApplicationContext@d1e604]; startup date [Fri Dec 16 12:02:08 CET 2011]; root of context hierarchy
16 déc. 2011 12:02:08 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [spring/config/BeanLocations.xml]
16 déc. 2011 12:02:09 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [spring/database/DataSource.xml]
16 déc. 2011 12:02:09 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [spring/database/Hibernate.xml]
16 déc. 2011 12:02:09 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [spring/beans/Stock.xml]
16 déc. 2011 12:02:09 org.springframework.context.support.AbstractApplicationContext obtainFreshBeanFactory
INFO: Bean factory for application context [org.springframework.context.support.ClassPathXmlApplicationContext@d1e604]: org.springframework.beans.factory.support.DefaultListableBeanFactory@2a5330
16 déc. 2011 12:02:09 org.springframework.core.io.support.PropertiesLoaderSupport loadProperties
INFO: Loading properties file from class path resource [properties/database.properties]
16 déc. 2011 12:02:09 org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@2a5330: defining beans [org.springframework.beans.factory.config.PropertyPlaceholderConfigurer#0,dataSource,sessionFactory,stockBo,stockDao]; root of factory hierarchy
16 déc. 2011 12:02:09 org.springframework.jdbc.datasource.DriverManagerDataSource setDriverClassName
INFO: Loaded JDBC driver: com.mysql.jdbc.Driver
16 déc. 2011 12:02:09 org.springframework.beans.factory.support.DefaultSingletonBeanRegistry destroySingletons
INFO: Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@2a5330: defining beans [org.springframework.beans.factory.config.PropertyPlaceholderConfigurer#0,dataSource,sessionFactory,stockBo,stockDao]; root of factory hierarchy
Exception in thread “main” org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘sessionFactory’ defined in class path resource [spring/database/Hibernate.xml]: Initialization of bean failed; nested exception is java.lang.NoClassDefFoundError: javax/transaction/TransactionManager
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:480)
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.NoClassDefFoundError: javax/transaction/TransactionManager
at java.lang.Class.getDeclaredMethods0(Native Method)
at java.lang.Class.privateGetDeclaredMethods(Unknown Source)
at java.lang.Class.privateGetPublicMethods(Unknown Source)
at java.lang.Class.getMethods(Unknown Source)
at java.beans.Introspector.getPublicDeclaredMethods(Unknown Source)
at java.beans.Introspector.getTargetMethodInfo(Unknown Source)
at java.beans.Introspector.getBeanInfo(Unknown Source)
at java.beans.Introspector.getBeanInfo(Unknown Source)
at org.springframework.beans.CachedIntrospectionResults.(CachedIntrospectionResults.java:220)
at org.springframework.beans.CachedIntrospectionResults.forClass(CachedIntrospectionResults.java:144)
at org.springframework.beans.BeanWrapperImpl.getCachedIntrospectionResults(BeanWrapperImpl.java:252)
at org.springframework.beans.BeanWrapperImpl.getPropertyDescriptorInternal(BeanWrapperImpl.java:282)
at org.springframework.beans.BeanWrapperImpl.isWritableProperty(BeanWrapperImpl.java:333)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1247)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1010)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:472)
… 14 more
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)
… 30 more
Thanks for the great tutorial! I have also posted some similar tutorials at bitbybitblog so let me know what you think. 🙂 Spring, hibernate, maven, tdd. Keep up the good work mate.
Great tutorial, got there in the end!
Thanks.
Can you please mention the jar files which you used in this project.
Thanks….
This is maven project, download the source code above and view the entire dependencies in pom.xml file
I got some problem. Anyone can help me!!!
Hibernate + Spring + Maven
hi mkyong thx for this great tutorial, im getting this error on both this and the annotated version of this example, any ideas ??
Sorry to bother, but my error was at my pom.xml thx!!
I want to to use hibernate code generation configuration to generate model but this example do not have cfg.xml.
May i know how to use hibernate code generation configuration to generate model for this example ?
successfully generate the model using hibernate code generation configuration already.
Tutorials very useful. It help me a lot.
Refer to this JBoss tools tutorial to generate hibernate code.
Hi Mkyong,
Thanks for your tutorials, and helped me a lot in day to day activities. Is it possible to post Spring MVC and Hibernate integration? it will be of greate help if you could do that.
thanks.
It’s simply a Spring + Hibernate integrate, refer to Spring tutorials
Hi,
Thanks for this helpful tutorial, I was wondering how can I enable caching while executing select statements?
I entered this in Hibernate.xml
true
true
org.hibernate.cache.EhCacheProvider
and I entered this in the findByStockCode method :
getHibernateTemplate().setCacheQueries(true);
but in App.java if call the findByStockCode method multiple times for the same id then it executes the select statement multiple times, I want it to execute only once.
Any ideas how to do it?
Thanks !
weird the xml pre tags doesnt seem to work…
hibernate.cache.use_second_level_cache = true
hibernate.cache.use_query_cache = true
hibernate.cache.provider_class = org.hibernate.cache.EhCacheProvider
Thanks for your idea, will publish some Hibernate + caching tutorials in future.
Thank you very much .
We need Spring Security intergation with Hibernate ..
Hi Mkyong,
Thank you this great tutorial. I found one interesting issue in database.properties. It is only working for the default port which is 3306. i.e.
jdbc.url=jdbc:mysql://localhost:3306/mkyong
I have tried created a exactly same database under port 3307 and switched url to 3307. I got a error said “Table ‘mkyong.stock’ doesn’t exist”
Thanks,
Xin
but if the database under 3306 exist, even url points to 3307 (jdbc.url=jdbc:mysql://localhost:3307/mkyong). The data actually was saved into table under 3306.
Xin
Hey Mkyong, these are the best tutorials I’ve ever read it. Your tutorials for dummies are so cool and so easy to understand.
Thanks a lot.
RASKA.
Ok, i solved it.
I have to add in my pom.xml this dependencys to get this thing work!
org.slf4j
slf4j-log4j12
1.6.1
org.slf4j
slf4j-api
1.6.1
javassist
javassist
3.4.GA
true
If i am correct, please change the pom.xml tutorial so other people dont get this error!
Thanks!
Excellent tutorial! really thank you.
One question.
I use maven and i have slf4j in my maven dependencys on the project.
But i still get this 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]:
Caused by: org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [org.springframework.orm.hibernate3.LocalSessionFactoryBean]: Constructor threw exception; nested exception is java.lang.NoClassDefFoundError: org/slf4j/impl/StaticLoggerBinder
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:115)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:61)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:877)
… 16 more
any ideas?
I think the solution is to add this on the POM xml
org.slf4j
slf4j-log4j12
1.6.1
org.slf4j
slf4j-api
1.6.1
javassist
javassist
3.4.GA
true
Its work for me!
What if i have no POM.xml file? =O
The download example is a Maven style project, if you prefer Ant or others, just handle your dependency properly, the code and logic is still apply well.
Salut Juan
I have the same probleme.
in the “javassist” dependency to add, what the taglib of the “true” ?
think you
Java is error stack, refer to last caused by, not the first error message.
I am getting the following error, would appreciate your help
Exception in thread “main” org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘sessionFactory’ defined in class path resource [resources/database/Hibernate.xml]: Invocation of init method failed; nested exception is java.lang.IllegalAccessError
Java error messages are in stack, when finding the root caused of the problem, you should always refer to the latest “Caused By”, not the first few lines.
Hi mkyong! before anything let me say you’re amazing! all of your articles are easy to understand and follow!
Now let me ask you a question, what view of eclipse do you use? Java or JavaEE?
Which of them you recomend me?
Thanks a lot!
Get a “Eclipse IDE for Java EE Developers”, it bundles everything you need.
Missing artifact hibernate:hibernate3:jar:3.2.3.GA:compile
I have the same error !
The following artifacts could not be resolved: hibernate:hibernate3:jar:3.2.3.GA
Java, keep changing the things, try search hibernate at http://search.maven.org/
Hi,
Mkyong is rigth. Try this:
org.hibernate
hibernate
3.2.3.ga
Regards,
Tsvetan
Hi 🙂
You are right
Thanx
Easy to understand , tnks
I add the resources to the class path and everything goes well. Thanks for your wonderful post, Well Done !!!!
This is the error that I get once I run it. Please help me to figure it out. I am waiting for your help.
Thanks Bahador
Caused by: java.io.FileNotFoundException: class path resource [spring/config/BeanLocations.xml] cannot be opened because it does not exist
at org.springframework.core.io.ClassPathResource.getInputStream(ClassPathResource.java:143)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:336)
… 13 more
Hi,
I’ve got a database with a lot of table. Is there a way to generate Model, DO and DAO ?
Thanks!
Yes, please refer to Hibernate Tool.
Thanks, I manage to solve my problem with another example from your site !
easy to follow and to understand. thanks
Very easy to follow and to undestand. Thanks
Hello,
I have a problem with this example !! when I added the dependencies throw maven, maven didn’t update the eclipse classpath, so when I try to use HibernateDaoSupport i got erreur ??
Do you have any idea how can I solve this issue ??
best regards,
Pls show me your error message.
Thanks it’s resolved now !! i just run mvn eclipse:eclipse and every things is fine now !!
best regards
Following jars added in /WEB-INF/lib
1)hibernate3.jar
2)jta.jar
3)jaxen-1.1-beta-4.jar
4)ehcache-1.1.jar
well done.Thanks a ton.
What different design patterns were followed to build this sample project?
just a Spring and Hibernate integration, not really any design patterns to follow.
how will I know if Maven, MySQL and Eclipse IDE are installed and configured properly? Thanks
It’s depend what you want to configure?
For basic verification, do so :
Maven – In command prompt or shell, type mvn -version.
Eclipse IDE – Until you can viewing the Eclipse GUI 🙂
MySQL – Use command or admin GUI to connect it.
Hi Guys!
when I type $mvn test I get:
1 required artifact is missing.
for artifact:
com.mkyong.common:SpringExample:jar:1.0-SNAPSHOT
Can you help me?
It look like your Maven folder structure is incorrect, did you tried $mvn build? Please zip and send me your example for review.
I get the following exception when I run App.java, form both the command line and within eclipse.
Exception in thread “main” org.springframework.dao.DataAccessResourceFailureException: Cannot open connection; nested exception is org.hibernate.exception.JDBCConnectionException: Cannot open connection
at org.springframework.orm.hibernate3.SessionFactoryUtils.convertHibernateAccessException(SessionFactoryUtils.java:627)
at org.springframework.orm.hibernate3.HibernateAccessor.convertHibernateAccessException(HibernateAccessor.java:412)
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.pm.user.UserDaoImp.save(UserDaoImp.java:12)
at com.pm.app.app.main(app.java:26)
oh, I solve it!
I always appreciate many useful resources 😀
And how did you solve it ?
I get the following message when I run the App.java
Error creating bean with name ‘sessionFactory’ defined in class path resource [spring/database/Hibernate.xml]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [org.springframework.orm.hibernate3.LocalSessionFactoryBean]: Constructor threw exception; nested exception is java.lang.NoClassDefFoundError: org/slf4j/LoggerFactory
I want to solve this problem. Thanks
You are missing the slf4j dependency, just include it manually if you are not using Maven.
http://www.slf4j.org/
This doesn´t solve the problem
Hi, I download you example but I get the following exception when I run the project with tomcat:
Have you any idea??? can you help me????
Read this article, https://mkyong.com/hibernate/java-lang-nosuchmethoderror-org-objectweb-asm-classwriter/
You may have an old asm.jar, try upgrade it. Are you using Maven? It suppose get the latest asm library for you. Hope help.
Jb would’ve download with maven this dependency
javax.transaction
jta
1.1
I get the following exception when I run App.java, form both the command line and within eclipse.
Obviously, you do not have Hibernate library, make sure it’s in your project library dependency folder.
Very well explained and easy to follow. Thanks.
Very usefull, many thanks.