Maven + (Spring + Hibernate) Annotation + MySql Example
In last tutorial, you use Maven to create a simple Java project structure, and demonstrate how to use Hibernate in Spring framework to do the data manipulation works(insert, select, update and delete) in MySQL database. In this tutorial, you will learn how to do the same thing in Spring and Hibernate annotation way.
Prerequisite requirement
– Installed and configured Maven, MySQL, Eclipse IDE.
Final project structure
Your final project file structure should look exactly like following, if you get lost in the folder structure creation, please review this folder structure here.
1. Table creation
Create a ‘stock’ table in MySQL database. SQL statement as follow :
CREATE TABLE `mkyong`.`stock` (
`STOCK_ID` int(10) unsigned NOT NULL AUTO_INCREMENT,
`STOCK_CODE` varchar(10) NOT NULL,
`STOCK_NAME` varchar(20) NOT NULL,
PRIMARY KEY (`STOCK_ID`) USING BTREE,
UNIQUE KEY `UNI_STOCK_NAME` (`STOCK_NAME`),
UNIQUE KEY `UNI_STOCK_ID` (`STOCK_CODE`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8;
2. Project File Structure
Create a quick project file structure with Maven command ‘mvn archetype:generate‘, see example here. Convert it to Eclipse project (mvn eclipse:eclipse) and import it into Eclipse IDE.
E:\workspace>mvn archetype:generate
[INFO] Scanning for projects...
...
Choose a number:
(1/2/3....) 15: : 15
...
Define value for groupId: : com.mkyong.common
Define value for artifactId: : HibernateExample
Define value for version: 1.0-SNAPSHOT: :
Define value for package: com.mkyong.common: : com.mkyong.common
[INFO] OldArchetype created in dir: E:\workspace\HibernateExample
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESSFUL
[INFO] ------------------------------------------------------------------------
3. Pom.xml file configuration
Add the Spring, Hibernate, Annotation and MySQL and their dependency in the Maven’s pom.xml file.
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.mkyong.common</groupId>
<artifactId>SpringExample</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<name>SpringExample</name>
<url>http://maven.apache.org</url>
<repositories>
<repository>
<id>JBoss repository</id>
<url>http://repository.jboss.com/maven2/</url>
</repository>
</repositories>
<dependencies>
<!-- JUnit testing framework -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<!-- Spring framework -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring</artifactId>
<version>2.5.6</version>
</dependency>
<!-- Spring AOP dependency -->
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>2.2</version>
</dependency>
<!-- MySQL database driver -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.9</version>
</dependency>
<!-- Hibernate framework -->
<dependency>
<groupId>hibernate</groupId>
<artifactId>hibernate3</artifactId>
<version>3.2.3.GA</version>
</dependency>
<!-- Hibernate annotation -->
<dependency>
<groupId>hibernate-annotations</groupId>
<artifactId>hibernate-annotations</artifactId>
<version>3.3.0.GA</version>
</dependency>
<dependency>
<groupId>hibernate-commons-annotations</groupId>
<artifactId>hibernate-commons-annotations</artifactId>
<version>3.0.0.GA</version>
</dependency>
<!-- Hibernate library dependecy start -->
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.2.1</version>
</dependency>
<dependency>
<groupId>antlr</groupId>
<artifactId>antlr</artifactId>
<version>2.7.7</version>
</dependency>
<!-- Hibernate library dependecy end -->
</dependencies>
</project>
4. Model & BO & DAO
The Model, Business Object (BO) and Data Access Object (DAO) pattern is useful to identify the layer clearly to avoid mess up the project structure.
Stock Model (Annotation)
A Stock model annotation class to store the stock data.
package com.mkyong.stock.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
@Entity
@Table(name = "stock", catalog = "mkyong", uniqueConstraints = {
@UniqueConstraint(columnNames = "STOCK_NAME"),
@UniqueConstraint(columnNames = "STOCK_CODE") })
public class Stock implements java.io.Serializable {
private Integer stockId;
private String stockCode;
private String stockName;
public Stock() {
}
public Stock(String stockCode, String stockName) {
this.stockCode = stockCode;
this.stockName = stockName;
}
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "STOCK_ID", unique = true, nullable = false)
public Integer getStockId() {
return this.stockId;
}
public void setStockId(Integer stockId) {
this.stockId = stockId;
}
@Column(name = "STOCK_CODE", unique = true, nullable = false, length = 10)
public String getStockCode() {
return this.stockCode;
}
public void setStockCode(String stockCode) {
this.stockCode = stockCode;
}
@Column(name = "STOCK_NAME", unique = true, nullable = false, length = 20)
public String getStockName() {
return this.stockName;
}
public void setStockName(String stockName) {
this.stockName = stockName;
}
@Override
public String toString() {
return "Stock [stockCode=" + stockCode + ", stockId=" + stockId
+ ", stockName=" + stockName + "]";
}
}
Stock Business Object (BO))
Stock business object (BO) interface and implementation, it’s used to store the project’s business function, the real database operations (CRUD) works should not involved in this class, instead it has a DAO (StockDao) class to do it.
package com.mkyong.stock.bo;
import com.mkyong.stock.model.Stock;
public interface StockBo {
void save(Stock stock);
void update(Stock stock);
void delete(Stock stock);
Stock findByStockCode(String stockCode);
}
Make this class as a bean “stockBo” in Spring Ioc container, and autowire the stock dao class.
package com.mkyong.stock.bo.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.mkyong.stock.bo.StockBo;
import com.mkyong.stock.dao.StockDao;
import com.mkyong.stock.model.Stock;
@Service("stockBo")
public class StockBoImpl implements StockBo{
@Autowired
StockDao stockDao;
public void setStockDao(StockDao stockDao) {
this.stockDao = stockDao;
}
public void save(Stock stock){
stockDao.save(stock);
}
public void update(Stock stock){
stockDao.update(stock);
}
public void delete(Stock stock){
stockDao.delete(stock);
}
public Stock findByStockCode(String stockCode){
return stockDao.findByStockCode(stockCode);
}
}
Stock Data Access Object
A Stock DAO interface and implementation. In last tutorial, you DAO classes are directly extends the “HibernateDaoSupport“, but it’s not possible to do it in annotation mode, because you have no way to auto wire the session Factory bean from your DAO class. The workaround is create a custom class (CustomHibernateDaoSupport) and extends the “HibernateDaoSupport” and auto wire the session factory, and your DAO classes extends this class.
package com.mkyong.stock.dao;
import com.mkyong.stock.model.Stock;
public interface StockDao {
void save(Stock stock);
void update(Stock stock);
void delete(Stock stock);
Stock findByStockCode(String stockCode);
}
package com.mkyong.util;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
public abstract class CustomHibernateDaoSupport extends HibernateDaoSupport
{
@Autowired
public void anyMethodName(SessionFactory sessionFactory)
{
setSessionFactory(sessionFactory);
}
}
package com.mkyong.stock.dao.impl;
import java.util.List;
import org.springframework.stereotype.Repository;
import com.mkyong.stock.dao.StockDao;
import com.mkyong.stock.model.Stock;
import com.mkyong.util.CustomHibernateDaoSupport;
@Repository("stockDao")
public class StockDaoImpl extends CustomHibernateDaoSupport implements StockDao{
public void save(Stock stock){
getHibernateTemplate().save(stock);
}
public void update(Stock stock){
getHibernateTemplate().update(stock);
}
public void delete(Stock stock){
getHibernateTemplate().delete(stock);
}
public Stock findByStockCode(String stockCode){
List list = getHibernateTemplate().find(
"from Stock where stockCode=?",stockCode
);
return (Stock)list.get(0);
}
}
5. Resource Configuration
Create a ‘resources‘ folder under ‘project_name/main/java/‘, Maven will treat all files under this folder as resources file. It will used to store the Spring, Hibernate and others configuration file.
Spring Configuration
Database related….
Create a properties file (database.properties) for the database details, put it into the “resources/properties” folder. It’s good practice disparate the database details and Spring bean configuration into different files.
database.properties
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mkyong
jdbc.username=root
jdbc.password=password
Create a “dataSource” bean configuration file (DataSource.xml) for your database, and import the properties from database.properties, put it into the “resources/database” folder.
DataSource.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>properties/database.properties</value>
</property>
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
</beans>
Hibernate related….
Create a session factory bean configuration file (Hibernate.xml), put it into the “resources/database” folder. In annotation you have to use the AnnotationSessionFactoryBean, instead of LocalSessionFactoryBean, and specify your annotated model classes in ‘annotatedClasses‘ property instead of ‘mappingResources‘ property.
Hibernate.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<!-- Hibernate session factory -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSource"/>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
<property name="annotatedClasses">
<list>
<value>com.mkyong.stock.model.Stock</value>
</list>
</property>
</bean>
</beans>
Import all the Spring’s beans configuration files into a single file (BeanLocations.xml), put it into the “resources/config” folder.
BeanLocations.xml
Import the Spring database configuration and enable the Spring’s auto scan feature.
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<!-- Database Configuration -->
<import resource="../database/DataSource.xml"/>
<import resource="../database/Hibernate.xml"/>
<!-- Auto scan the components -->
<context:component-scan
base-package="com.mkyong.stock" />
</beans>
6. Run it
You have all the files and configurations , run it.
package com.mkyong.common;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.mkyong.stock.bo.StockBo;
import com.mkyong.stock.model.Stock;
public class App
{
public static void main( String[] args )
{
ApplicationContext appContext =
new ClassPathXmlApplicationContext("spring/config/BeanLocations.xml");
StockBo stockBo = (StockBo)appContext.getBean("stockBo");
/** insert **/
Stock stock = new Stock();
stock.setStockCode("7668");
stock.setStockName("HAIO");
stockBo.save(stock);
/** select **/
Stock stock2 = stockBo.findByStockCode("7668");
System.out.println(stock2);
/** update **/
stock2.setStockName("HAIO-1");
stockBo.update(stock2);
/** delete **/
stockBo.delete(stock2);
System.out.println("Done");
}
}
output
Hibernate: insert into mkyong.stock (STOCK_CODE, STOCK_NAME) values (?, ?)
Hibernate: select stock0_.STOCK_ID as STOCK1_0_,
stock0_.STOCK_CODE as STOCK2_0_, stock0_.STOCK_NAME as STOCK3_0_
from mkyong.stock stock0_ where stock0_.STOCK_CODE=?
Stock [stockCode=7668, stockId=11, stockName=HAIO]
Hibernate: update mkyong.stock set STOCK_CODE=?, STOCK_NAME=? where STOCK_ID=?
Hibernate: delete from mkyong.stock where STOCK_ID=?
Done
Conclusion
All Spring, Hibernate related classes and configuration files are annotated, it just left the database details in XML file. Should you know how to annotate the database configuration details, please let me know. Personally, i do not use annotation feature much, because somehow you may need some workaround for certain situation, like ‘CustomHibernateDaoSupport’ extends ‘HibernateDaoSupport’ above. The mature developed XML file in Spring and Hibernate. is more preferably.
Hello,
My problem is that Eclipse doesnt know import javax.persistence.Column and others imports in Class Model and annotations in class Model I dont know why, please any help.
org.hibernate.javax.persistence
hibernate-jpa-2.0-api
1.0.1.Final
javax.persistence
persistence-api
1.0
Hi, Can you just reply whether the same hibernate integration approach will work in spring boot 2.0.2 version?
is it necessary to make configuration by xml file. is it possible to make complete configuration through annotations.
I tried following along with this program for my own web mvc application and getting the error “No bean named ‘stockBo’ available”. I’ve looked everywhere online and tried a number of combinations changing my web.xml, spring-mvc.xml, spring-config.xml and some annotation changes but nothing is working. Any clues?
Thanks lot , it’s is successful tutorial
Hello . Can you please update it Spring 3 and Hibernate 4! By the way it’s Great Work!
Thanks a lot for the tuto!
Failed to convert property value of type ‘java.util.ArrayList’ to required type ‘java.lang.Class[]’ for property ‘annotatedClasses’
unable to run please help
thank you. Could you please do the same great example using the latest hibernate and latest spring?
Thanks for the tutorilal. when i am trying to run app.java i am getting following error. This is because auto intrement coloumn not getting populated.
Exception in thread “main” org.springframework.jdbc.UncategorizedSQLException: Hibernate operation: could not insert: [com.mkyong.stock.model.Stock]; uncategorized SQLException for SQL [insert into stock1 (STOCK_CODE, STOCK_NAME) values (?, ?)]; SQL state [99999]; error code [17004]; Invalid column type: getInt not implemented for class oracle.jdbc.driver.T4CRowidAccessor; nested exception is java.sql.SQLException: Invalid column type: getInt not implemented for class oracle.jdbc.driver.T4CRowidAccessor
at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:83)
at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:80)
at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:80)
at org.springframework.orm.hibernate3.HibernateAccessor.convertJdbcAccessException(HibernateAccessor.java:424)
at org.springframework.orm.hibernate3.HibernateAccessor.convertHibernateAccessException(HibernateAccessor.java:410)
at org.springframework.orm.hibernate3.HibernateTemplate.doExecute(HibernateTemplate.java:424)
at org.springframework.orm.hibernate3.HibernateTemplate.executeWithNativeSession(HibernateTemplate.java:374)
at org.springframework.orm.hibernate3.HibernateTemplate.save(HibernateTemplate.java:694)
at com.mkyong.stock.dao.impl.StockDaoImpl.save(StockDaoImpl.java:17)
at com.mkyong.stock.bo.dao.impl.StockBoImpl.save(StockBoImpl.java:21)
at com.mkyong.stock.model.App.main(App.java:18)
Caused by: java.sql.SQLException: Invalid column type: getInt not implemented for class oracle.jdbc.driver.T4CRowidAccessor
at oracle.jdbc.driver.Accessor.unimpl(Accessor.java:412)
at oracle.jdbc.driver.Accessor.getInt(Accessor.java:529)
at oracle.jdbc.driver.OracleReturnResultSet.getInt(OracleReturnResultSet.java:388)
at org.hibernate.id.IdentifierGeneratorFactory.get(IdentifierGeneratorFactory.java:50)
at org.hibernate.id.IdentifierGeneratorFactory.getGeneratedIdentity(IdentifierGeneratorFactory.java:35)
at org.hibernate.id.IdentityGenerator$GetGeneratedKeysDelegate.executeAndExtract(IdentityGenerator.java:74)
at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:33)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2158)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2638)
at org.hibernate.action.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:48)
at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:248)
at org.hibernate.event.def.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:298)
at org.hibernate.event.def.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:181)
at org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:107)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:187)
at org.hibernate.event.def.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:33)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:172)
at org.hibernate.event.def.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:27)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:70)
at org.hibernate.impl.SessionImpl.fireSave(SessionImpl.java:535)
at org.hibernate.impl.SessionImpl.save(SessionImpl.java:523)
at org.hibernate.impl.SessionImpl.save(SessionImpl.java:519)
at org.springframework.orm.hibernate3.HibernateTemplate$12.doInHibernate(HibernateTemplate.java:697)
at org.springframework.orm.hibernate3.HibernateTemplate.doExecute(HibernateTemplate.java:419)
… 5 more
The pom file doesnt work….include this
org.hibernate
hibernate-entitymanager
4.3.8.Final
the pom file is this project will not run correctly….try including this dependency…
org.hibernate
hibernate-entitymanager
4.3.8.Final
I try to add JSF 2 in this project, but i’ve a lot of problems, it’s very hard to do it.
I think a structure of projet is differente
hello to you i’m learning how to use Spring Framework but i’ve some problems with this tutorial. When i launch the example builded i always encounter the same problem. Can someone help me please ? the message shown by Spring Tool Suite in the following :
sept. 20, 2014 11:28:13 AM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFOS: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@171fc7e: startup date [Sat Sep 20 11:28:12 WAT 2014]; root of context hierarchy
sept. 20, 2014 11:28:13 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFOS: Loading XML bean definitions from class path resource [spring/config/BeansLocations.xml]
sept. 20, 2014 11:28:13 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFOS: Loading XML bean definitions from class path resource [spring/database/DataSource.xml]
sept. 20, 2014 11:28:13 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFOS: Loading XML bean definitions from class path resource [spring/database/Hibernate.xml]
sept. 20, 2014 11:28:14 AM org.springframework.core.io.support.PropertiesLoaderSupport loadProperties
INFOS: Loading properties file from class path resource [properties/database.properties]
sept. 20, 2014 11:28:14 AM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFOS: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@1494225: defining beans [org.springframework.beans.factory.config.PropertyPlaceholderConfigurer#0,dataSource,sessionFactory,stockBo,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.internalPersistenceAnnotationProcessor,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor]; root of factory hierarchy
Exception in thread “main” java.lang.NoSuchMethodError: org.springframework.beans.factory.annotation.InjectionMetadata.(Ljava/lang/Class;)V
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.findPersistenceMetadata(PersistenceAnnotationBeanPostProcessor.java:350)
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.postProcessMergedBeanDefinition(PersistenceAnnotationBeanPostProcessor.java:296)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyMergedBeanDefinitionPostProcessors(AbstractAutowireCapableBeanFactory.java:840)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:495)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:626)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:932)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:479)
at org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:83)
at com.mkyong.common.App.main(App.java:13)
App.main is my main class
Thanks
Hi i am getting below exception
Caused by: java.lang.ClassNotFoundException: org.aopalliance.intercept.MethodInterceptor
I tried to run this in Eclipse. I did “Run as > Maven build” with “clean install” in the target line. It built correctly and ran the unit tests, but it didn’t execute. I tried pressing the green eclipse button, but it doesn’t seem to know to run App.java. I looked under External tools and didn’t find the command line. I’m using Eclipse Kepler.
Hi, good tuto thanks for your effort, but i have question about how can i automatically generate table by using Hibernate, can you help me plz
Hi! I´ve my hibernate configuration inside my spring-context, but after a little time of use I´m getting the too many connections error. Here is my code:
Spring context:
com.proximate.model.Usuarios
org.hibernate.dialect.MySQLDialect
true
true
and here is how I use my session factory inside my dao:
private SessionFactory sessionFactory;
private HibernateTemplate hibernateTemplate;
public SessionFactory getSessionFactory() {
return sessionFactory;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.hibernateTemplate = new HibernateTemplate(sessionFactory);
}
Query query = hibernateTemplate.getSessionFactory().getCurrentSession().createSQLQuery(“SELECT ID FROM usuarios”);
Integer cantidad = new Integer(((BigInteger) query.uniqueResult()).intValue());
Why is my code opening so many connections. I heard that using a HibernateUtil class to load a session after logging might be what I need, but how do you implement it when using spring??
Thanks in advance!!
guys, I’m hitting the wall with this exception ” java.lang.ClassNotFoundException: javax.annotation.CheckReturnValue” just after trying to run the App file, can anyone help plz
Hi, I write my small contribution:
We have to change 2 dependences in pom.xml
BONUS:
if you want to install javaee.jar in your repository just execute the next program on shell:
mvn install:install-file -Dfile= -DgroupId=org.javax -DartifactId=javaee -Dversion=1.0 -Dpackaging=jar
then in pom.xml put the next dependency:
thank for advice.
CharlyR
the command was bad edited, please use this example:
mvn install:install-file -Dfile=./src/main/resources/javaee.jar -DgroupId=org.javax -DartifactId=javaee -Dversion=1.0 -Dpackaging=jar
“In last tutorial, you DAO classes are directly extends the “HibernateDaoSupport“, but it’s not possible to do it in annotation mode, because you have no way to auto wire the session Factory bean from your DAO class.”
It works for me:
“A Stock DAO interface and implementation. In last tutorial, you DAO classes are directly extends the “HibernateDaoSupport“, but it’s not possible to do it in annotation mode, because you have no way to auto wire the session Factory bean from your DAO class.”
It works for me:
Hi .thanks for this post, it’s very useful.
Question : how do we host maven + spring + hibernate in GAE?
Hi. is there an easier way to automatically scan and use any @Entity marked objects instead of listing all of them in a sessionFactory using
??
Can u are tell me, why i am gating these error:
Feb 19, 2013 4:51:58 PM org.apache.catalina.core.AprLifecycleListener init
INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: C:\Program Files\Java\jre7\bin;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files\TortoiseSVN\bin;C:\Program Files\Java\jdk1.6.0_32\bin;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;.
Feb 19, 2013 4:52:02 PM org.apache.tomcat.util.digester.SetPropertiesRule begin
WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property ‘source’ to ‘org.eclipse.jst.jee.server:SpringTest’ did not find a matching property.
Feb 19, 2013 4:52:11 PM org.apache.coyote.http11.Http11Protocol init
INFO: Initializing Coyote HTTP/1.1 on http-8080
Feb 19, 2013 4:52:11 PM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 21829 ms
Feb 19, 2013 4:52:12 PM org.apache.catalina.core.StandardService start
INFO: Starting service Catalina
Feb 19, 2013 4:52:12 PM org.apache.catalina.core.StandardEngine start
INFO: Starting Servlet Engine: Apache Tomcat/6.0.32
Feb 19, 2013 4:52:15 PM org.apache.catalina.core.StandardContext listenerStart
SEVERE: Error configuring application listener of class org.springframework.web.context.ContextLoaderListener
java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1680)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1526)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4148)
at org.apache.catalina.core.StandardContext.start(StandardContext.java:4704)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1053)
at org.apache.catalina.core.StandardHost.start(StandardHost.java:840)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1053)
at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:463)
Hi everyone/Mkyong.com
I configured new SpringIDE with Maven and i want to write simple web based application.but when i am going to run my application ,there,it was showing some error(I attached in below)whereas ,without SpringIDE and Maven it was ok….
I already checked these solution;
A>In web.xml ,ContextLoaderListener is configured or not.
B> I am using these software
1.eclipse-jee-juno-win32-x86_64
2.apache-maven-3.0.4-bin,
3.OS Window7-64bit
Can u are tell me, why i am gating these error:
Feb 19, 2013 4:51:58 PM org.apache.catalina.core.AprLifecycleListener init
INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: C:\Program Files\Java\jre7\bin;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files\TortoiseSVN\bin;C:\Program Files\Java\jdk1.6.0_32\bin;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;.
Feb 19, 2013 4:52:02 PM org.apache.tomcat.util.digester.SetPropertiesRule begin
WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property ‘source’ to ‘org.eclipse.jst.jee.server:SpringTest’ did not find a matching property.
Feb 19, 2013 4:52:11 PM org.apache.coyote.http11.Http11Protocol init
INFO: Initializing Coyote HTTP/1.1 on http-8080
Feb 19, 2013 4:52:11 PM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 21829 ms
Feb 19, 2013 4:52:12 PM org.apache.catalina.core.StandardService start
INFO: Starting service Catalina
Feb 19, 2013 4:52:12 PM org.apache.catalina.core.StandardEngine start
INFO: Starting Servlet Engine: Apache Tomcat/6.0.32
Feb 19, 2013 4:52:15 PM org.apache.catalina.core.StandardContext listenerStart
SEVERE: Error configuring application listener of class org.springframework.web.context.ContextLoaderListener
java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1680)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1526)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4148)
at org.apache.catalina.core.StandardContext.start(StandardContext.java:4704)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1053)
at org.apache.catalina.core.StandardHost.start(StandardHost.java:840)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1053)
at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:463)
This tutorial is quiet outdated now. Can you please update it Spring 3 and Hibernate 4
Hey, do you have an idea about this problem?? I can not unlock it demoralizes me: s
Thank you in advance
org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘sessionFactory’ defined in ServletContext resource [/WEB-INF/classes/config/spring/HibernateSessionFactory.xml]: Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property ‘annotatedClasses’ of bean class [org.springframework.orm.hibernate3.LocalSessionFactoryBean]: Bean property ‘annotatedClasses’ is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?
this is resolved I should use AnnotationSessionFactoryBean – Tks Mkyong For All
Hi Mkyong,
A very good example to understand the Spring + hibernate integration.
But as i was trying to build your project following errors are coming. Please help
D:\Project\SpringHibernateAnnotationExample\src\main\java\com\mkyong\util\CustomHibernateDaoSupport.java:[9,2] error: annotations are not supported in -source 1.3
could not parse error message: (use -source 5 or higher to enable annotations)
D:\Project\SpringHibernateAnnotationExample\src\main\java\com\mkyong\stock\bo\impl\StockBoImpl.java:10: error: annotations are not supported in -source 1.3
@Service(“stockBo”)
^
could not parse error message: (use -source 5 or higher to enable annotations)
D:\Project\SpringHibernateAnnotationExample\src\main\java\com\mkyong\stock\dao\impl\StockDaoImpl.java:11: error: annotations are not supported in -source 1.3
@Repository(“stockDao”)
^
could not parse error message: (use -source 5 or higher to enable annotations)
D:\Project\SpringHibernateAnnotationExample\src\main\java\com\mkyong\stock\model\Stock.java:6: error: static import declarations are not supported in -source 1.3
import static javax.persistence.GenerationType.IDENTITY;
^
could not parse error message: (use -source 5 or higher to enable static import declarations)
D:\Project\SpringHibernateAnnotationExample\src\main\java\com\mkyong\stock\model\Stock.java:11: error: annotations are not supported in -source 1.3
@Entity
^
Please help me in this direction.
Thanks
Varun
Nice Tutorial.
But can’t able to download the maven dependencies. Mr.Yong, please kindly update this tutorial with latest repository urls.
Thanks,
Hariharan
Thanks you are publishing very good tutorial all the time.