Maven + Spring + Hibernate + MySql Example
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







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.
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.
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!
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 – http://www.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
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 :D
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, http://www.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.
[...] Spring + Hibernate Integration Example to integrate Hibernate with Spring framework. [...]
[...] Annotation + MySql Example Written on March 31, 2010 at 3:12 pm by mkyong In last tutorial, you use Maven to create a simple Java project structure, and demonstrate how to use Hibernate in [...]
Very usefull, many thanks.