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.
Kindly, please support me.
How to resolve this folloewing Error:
” The type org.springframework.dao.DataAccessException cannot be resolved. It is indirectly referenced from required .class files”
which i wrote code is:
Java -
It is showing the above mentioned error & also:
The hierarchy of the type StudentDAOImpl is inconsistent
Also, in the class
What is actually happening here? We are autowiring SessionFactory. Isn’t that true.
If that is correct, then why can’t we declare it as below
ofcourse, I could not get this work. But curious in what way this declaration is different from what is declared in the post. Field autowiring vs method autowiring.
Yes, you can extend the
HibernateDaoSupportdirectly, but if any major DAO support is changed (may be you don’t want to use Hibernate now), all codes need to change accordingly. To create a extra DAO support class, you just need to maintain one DAO support file.Either ways will works, just choose one to suit your needs
Your posts are really helpful in understanding the concepts and keep up the good work.
I have a question here though, we actually annotated using @Service and @Repository but we are doing component scan. Are Service and Repository also considered as Components. If that is case, would that be wrong, if I use @Component instead of @Service and @Repository
Read this article – Spring auto scanning components.
They are all @Component, just different naming to easy maintain.
Hi..This is my first comment in this website. And i have been following all the tutorials they are indeed great and very useful.
While going through this tutorial and the previous one(w/o annotations) I saw you have separated the Bo layer and DAO layer. I don’t find the difference between both the layers and moreover both the interfaces (Bo and Dao) are exposing the same operations, can you please explain why do we need these two layers with a good example?
Hope you will respond soon.
Many Thanks…!
Babu
thanks,
found this example v useful.
tbh its not the first time I use great pages from mkyong!
Just went through this, thanks for the example. A couple issues I had:
1. The database.properties file somehow was not getting resolved, so eventually I just hard-coded those particular name-value pairs into DataSource.xml. Still not sure what the issue was.
2. Thanks to one of the posters above, the correct maven POM is very important here, so I am posting the exact one I used below:
1. Make sure “database.properties” is put at the correct folder.
2. Thanks for your input. Is my pom.xml in the download project not working?
I did not try the POM from the download folder, as I wanted to take things step by step….
re: database.properties – tried it in the folder recommended above, and when that did not work, I tried moving it around (including to “src” which in eclipse should have been on the classpath). No big deal
Thanks again for the tutorials, they are very good.
Good day,
I am a newbie in spring, hibernate and maven
I saved “Spring-Hibernate-Annotation-Example.zip” extracted if afterwards and then imported it into eclipse…
now, I am having problems since I do not have any of the libraries that has M2_REPO
when I check my “.m2/repository” I cannot see any jar file in it.
how can I get all the needed jar for this example? hope somebody can help me ^_^
You need to add M2_REPO in your Eclipse, once. Refer to this guide – http://www.mkyong.com/maven/how-to-configure-m2_repo-variable-in-eclipse-ide/
Thanks for the fast reply sir ^_^
I was able to set M2_REPO in my eclipse now.
Sorry for being a complete noob on maven, spring & hibernate (my background is only struts 1, ant)
How to I run this?
Below are the things I tried:
* mvn compile (SUCCESSFUL)
* mvn test (SUCCESSFUL)
* mvn install (SUCCESSFUL)
* mvn deploy (ERROR)
I am having this error
[INFO] ————————————————————————
[ERROR] BUILD ERROR
[INFO] ————————————————————————
[INFO] Failed to configure plugin parameters for: org.apache.maven.plugins:maven-deploy-plugin:2.4
check that the following section of the pom.xml is present and correct:
repo
Repository Name
scp://host/path/to/repo
repo
Repository Name
scp://host/path/to/repo
Cause: Class ‘org.apache.maven.artifact.repository.ArtifactRepository’ cannot be instantiated
[INFO] ————————————————————————
[INFO] For more information, run Maven with the -e switch
[INFO] ————————————————————————
[INFO] Total time: 11 seconds
[INFO] Finished at: Wed Dec 14 12:34:00 PHT 2011
[INFO] Final Memory: 14M/166M
[INFO] ————————————————————————
What else do I need sir to run/test this?
Thanks a lot and Godbless.
More Power ^_^
When I tried running App.java in eclipse I got the error below:
Make sure javee.jar (available from JDK) is in the classpath.
Create a Tomcat server in Eclipse, add your project and run it.
Thanks a lot sir
Got it working now
[ERROR] Failed to execute goal on project SpringExample: Could not resolve dependencies for project com.mkyong.common:SpringExample:jar:1.0-SNAPSHOT: Failed to collect dependencies for [junit:junit:jar:3.8.1 (test), org.springframework:spring:jar:2.5.6 (compile), cglib:cglib:jar:2.2 (compile), mysql:mysql-connector-java:jar:5.1.9 (compile), hibernate:hibernate3:jar:3.2.3.GA (compile), hibernate-annotations:hibernate-annotations:jar:3.3.0.GA (compile), hibernate-commons-annotations:hibernate-commons-annotations:jar:3.0.0.GA (compile), dom4j:dom4j:jar:1.6.1 (compile), commons-logging:commons-logging:jar:1.1.1 (compile), commons-collections:commons-collections:jar:3.2.1 (compile), antlr:antlr:jar:2.7.7 (compile)]: Failed to read artifact descriptor for hibernate:hibernate3:jar:3.2.3.GA: Could not transfer artifact hibernate:hibernate3:pom:3.2.3.GA from/to JBoss repositor
y (http://repository.jboss.com/maven2/): Access denied to: http://repository.jbo
ss.com/maven2/hibernate/hibernate3/3.2.3.GA/hibernate3-3.2.3.GA.pom -> [Help 1]
[ERROR]
I use maven 3.0.3
I got this error, please help
Thank in advance
Hi Mkyong,
Thank you for the great tutorial. Your blog is in my top training list. I have a small request:
Could you rewrite and post an updated “pom.xml”-file?
I read in JBoss’s blog that their repository “http://repository.jboss.com/maven2/” (which you use in the tutorial) is replaced with the new repository “https://repository.jboss.org/nexus/content/groups/”. So the current pom-file is not correct and the project does not run from the first attempt. I spent a lot of time until I find the correct dependencies. I hope that you will facilitate the other people if you update and rerun the project. Thank you in advance.
Regards,
Tsvetan
Thanks for your update, will review the related tutorials next month. Often times, technology is change too fast …
Hi
I have completed the tutorial I have rewritten the pom file.
I also downloaded mysql-5.5.16-win32.msi and mysql-workbench-gpl-5.2.35-win32.
pom.xml
4.0.0
com.mkyong.common
SpringExample
jar
1.0-SNAPSHOT
SpringExample
http://maven.apache.org
junit
junit
3.8.1
test
org.springframework
spring
2.5.6
cglib
cglib
2.2
mysql
mysql-connector-java
5.1.9
<!– hibernate hibernate3
3.2.3.GA –>
hibernate
hibernate-tools
3.2.3.GA
dom4j
dom4j
1.6.1
commons-logging
commons-logging
1.1.1
commons-collections
commons-collections
3.2.1
antlr
antlr
2.7.7
org.slf4j
slf4j-log4j12
1.6.2
javassist
javassist
3.4.GA
true
org.hibernate
hibernate-commons-annotations
3.2.0.Final
org.hibernate
hibernate-core
3.6.0.Final
org.glassfish.extras
javaee
3.1.1
Can you explain how to read datasource from tomcat server directory/external location instead of properties file
thanks
Krish
Hi again mkyong,
I don’t quite get this method:
@Autowired
public void anyMethodName(SessionFactory sessionFactory)
{
setSessionFactory(sessionFactory);
}
Is it being called by someone or there’s no need? Also, the @Autowired is used to locate the SessionFactory Bean on Hibernate.xml right?
Thanks in advance.
The reason I’m asking this is because I want to use multiple databases and thus multiple session factories (or at leaest thats my guess so far).
Im guessing this method is being called by some delegate in some internal process but… What if I want to set a different session factory?
Cheers!
Hi Chuck,
Check this article:
http://www.codelark.com/tag/hibernatedaosupport/
Maybe it should help to clarify your “anyMethodName” question.
Ah yes! thanks sfeher!
Refer to this Spring tutorial – http://www.mkyong.com/tutorials/spring-tutorials/
Find for “Spring AutoWiring Bean”
Thanks Mkyong, I’ll give it a look right away.
Hi, I’m new to Java world and Spring and Maven and Netbeans! (I’ve always been a Visual Studio programmer) and this is an excelent tutorial to get hooked up.
BUT… I’m trying to do a MVC Desktop Application, Model and Controller seem to work fine, but I’m having a hard time to get the data from the Controller to the View.
How can I use the Model and the Controller on the View with spring?, I have noticed that web apps use the dwr.xml to use Controller methods.
Thanks in advance!
I guess what im really asking is…
How to configurate spring beans configuration files to use thru different projects? In my particular case, how can I use classes from Model and Controller projects in the View project.
Or is it correct to instance a class the classic way?
Class obj = new Class();
Sorry, i don’t get your question. For non-related question please post at – http://javanullpointer.com/.
And also, you may need to know how Spring MVC works – http://www.mkyong.com/tutorials/spring-mvc-tutorials/
Thanks for responding…
And finally, I’ve found the solution and it’s quite simple. When you have different projects (Model, Controller, Desktop View)you have to move the file “BeanLocations.xml” to the project who is going to use those Beans…
In my case i had to move “BeanLocations.xml” from Controller to Desktop View project, and leave the Spring DB Configruation on the Controller.
I hope it make some sense, I’m new to Java world.
Excelent Tutorial BTW!
couldnt be more clear to understand, thank you
Hi,
I am getting following error for each downloaded example. Am I missing any configuration?
How you build this project? Normally, “mvn eclipse:eclipse =Dwtpversion=2.0″ will do the best.
Please help me! Im trying to use maven + hibernate + spring since last week and i only got error. Now i’m trying to use your tutorial. When i use mvn archetype:generate, i get this error:
If i use mvn eclipse:eclipse =Dwtpversion=2.0, i have this error:
What’s your Maven version? Try upgrade to latest maven version.
i’ve updated to maven 3.0.3 but mvn archetype:generate still failures. but mvn eclipse:eclipse works.
Access denied, bro.
JBoss public repository is changed to “https://repository.jboss.org/nexus/content/groups/public-jboss/”
I need one full project in spring with code and netbean supported +mysql database
Pls help me any body
Download this Maven style project, then convert it to NetBean.
Your tutorial saved my day!
Simple, clear, very helpful.
Applied on my NetBeans’ Swing + Spring 3 + Hibernate + postgresql
Many thanks for sharing!
Good to know that
I want to use HSQL database and I changed the database:properties file.
jdbc.driverClassName=org.hsqldb.jdbcDriver
jdbc.url=jdbc:hsqldb:hsql://localhost:8080
jdbc.username=sa
jdbc.password=
But I am taking this message
Could you HELP me? thanks a lot…
Post your last caused by.
[...] http://www.mkyong.com/spring/maven-spring-hibernate-annotation-mysql-example/ March 27th, 2011 in Misc [...]
Hi,
I couldnt solve the following issue
and need help please advise to get rid of this error.
My POM file includes also following dependencies.
javax.persistence
persistence-api
1.0
javax
javaee-api
6.0
************************************************************************************
Summary of error:
Unexpected exception parsing XML document from class path resource [spring/config/BeanLocations.xml]; nested exception is java.lang.ClassFormatError: Absent Code attribute in method that is not native or abstract in class file javax/persistence/GenerationType
************************************************************************************
Full stack trace:
Thank you for quick response.
you need javaee.jar from your J2EE SDK folder. See below link :
http://www.mkyong.com/hibernate/java-lang-classformaterror-absent-code-attribute-in-method-that-is-not-native-or-abstract-in-class-file/
Hi,
I tried this example with JSF, but the ‘stockBo’ is still NULL. What is wrong ?
Thanks.
@Component
@ManagedBean
@SessionScoped
public class StockBean {
@Autowired
private StockBo stockBo;
private Stock stock;
public void setStockBo(StockBo stockBo) {
this.stockBo= stockBo;
}
public void save() {
stockBo.save(stock);
}
…..
}
It may due to your JSF didn’t integrate Spring well, refer this guide for JSF 2.0 + Spring 2.5.x integration.
http://www.mkyong.com/jsf2/jsf-2-0-spring-integration-example/
Great Tutorial… but when i run it i have this error:
Exception in thread “main” java.lang.NoClassDefFoundError: Ljavax/transaction/TransactionManager;
Can you help me??
Thanks a lot
Flavio
hi, you need javaee.jar library , see below link
http://www.mkyong.com/hibernate/java-lang-classnotfoundexception-javax-transaction-transactionmanager/
Hey, it is wonderful tutorial. thanks for your post. Could you please tell how I can run it?
Thanks
Bahador
I´ve installed java_ee_sdk-6u1-windows.exe but I couldn’t find javaee.jar
where could I download this file?
It should be inside “JAVAEE_FOLDER\SDK\lib\javaee.jar” , for example “C:\Sun\SDK\lib\javaee.jar”
I put a new dependency at pom.xml
javax.persistence
persistence-api
1.0
I get the following error: class path resource [spring/config/BeanLocations.xml] cannot be opened because it does not exist
and all i have done is to import the entire project (with the classpath file) into Eclipse. What am i doing wrong?
Is this file exist in your project?
You can very well use @Autowire for the HibernateDaoSupport. Not on the setter though (it’s final) but you can use @Autowire on the constructor.
ApplicationContext appContext =
new ClassPathXmlApplicationContext(“config/BeanLocations.xml”);
could you put some light on this statement?
Thanks
Load the XML file and parse the content, if found any beans in the xml file, just load it into the Spring container.
Hi,
In the example, to insert a “Stock” object you create the instance just like below;
/** insert **/
Stock stock = new Stock();
But, isn’t it better to declare the Stock class as Spring component with the annatotion “@Component” and make the “Stock stock” decleration as @Autowired and use it like mentioned??
What is the differences or adv./disadv. between those usage??
Thanks…
yes, bro, you can enhance this example to use the Spring annotation for BO or DAO and auto-wired it.
http://www.mkyong.com/spring/spring-auto-scanning-components/
Different? Just different way to do the same thing, with Spring annotation, it’s more faster to arrived Rome
Thank you very much for your reply
. I like your posts, they really helps me. Do you think to post a tuto about gwt+spring integration
, I am trying to do it and have some problems, it would help me.
Thanks for the kind word, will working on the GWT tutorial in the future.
When can we expect this tutorial?
GWT + Hibernate; Can’t wait!
Great job!
Thanks Mkyong, I wonder if you provided a lesson for GWT + Spring + Hibernate + MySql. Since I have some issues for it as well, and I’ve never found a useful tutorial.
Thanks
Bahador Biglari
Sorry, i’m not familiar with GWT as well :p, will study it soon
Thank you very much. It helps me a lot.
Exception in thread “main” org.springframework.beans.factory.BeanDefinitionStoreException: Unexpected exception parsing XML document from class path resource [spring/config/BeanLocations.xml]; nested exception is java.lang.ClassFormatError: Absent Code attribute in method that is not native or abstract in class file javax/persistence/GenerationType
You should use javaee.jar from sun-library, because the other javaees don’t have all
necessary classes (you can compile but during run you get errors).
you can write for dependency so:
javax
javaee
1.5.0
system
C:/SUN/SDK/lib/javaee.jar
I think so you can run the app.
best
Parviz
Hi, I’ve been looking for the explanation between @Service @Repository,
and often I end up with saying HQL/SQL are done in @Repository (DAO)
and @Service will inject with multiple dao (repository)
do you have any example on multiple dao in @Service?
because it would give better view on how to apply multiple dao in @Service (eg. joining multiple tables, do we do this in @Service or @Repository?)
*confused*
Thanks in advance
All @Repository,@Service or @Controller are belong to @Component. A good practice is declare the @Repository,@Service or @Controller for a specified layer to make your code more easier to understand.
You may interest to read this article – http://www.mkyong.com/spring/spring-auto-scanning-components/
Hi
I do understand both @Service & @Repository are @Component
but what I would like to see, is the application of @Service & @Repository from the DDD point-of-view (involving more than 1 dao, which this is what I couldn’t find on the internet)
Thanks
Just declare the @Repository to any dao layers; @Service to business layers, it’s for convention and good practice, why you want to find an application to demo of it?
Hi,
because I couldn’t get hold on how to @Service implementation works.
btw, I think I found some related sample app here
http://www.infoq.com/articles/ddd-in-practice
Thanks
And I found this log message together . Could you help me please
Hi, you are missing of the javaee.jar library, see this article http://www.mkyong.com/hibernate/java-lang-classnotfoundexception-javax-transaction-transactionmanager/
P.S Sorry, i didnt mention this at the article.
Actually, this didn’t work for me….I ended up using:
org.apache.openejb
javaee-api
5.0-2
jar
provided
Since you didn’t mention what “didn’t work” for you, so i can’t make any comments on it, this example is tested and worked well in my development environment. However, thanks for sharing your extra information
Hi,
thank you for your tuto.
But i’ve got an error when trying to compile App.java :
INFO: Loading XML bean definitions from class path resource [spring/config/BeanLocations.xml]
Exception in thread “main” org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path resource [spring/config/BeanLocations.xml]; nested exception is java.io.FileNotFoundException: class path resource [spring/config/BeanLocations.xml] cannot be opened because it does not exist
I tryed but I can’t figure it out.
Can you help me?
Look like the resource path error, did you compile it with Maven build before run? e.g, mvn eclipse:eclipse
Hi,
Thank you for your response.
No, I’ve build it like a java application directly in eclipse.
I’ll try something else.
Chesko
The attached is a maven, eclipse project, use Maven to build, it will do everything for use.
Hi,
thank you .
Tell me.
what should I do if I want to use spring 3 ?
I guess that I have to change JRE in build Path to 1.5 or higher?
And Is it a good thing to use spring 3 ?
Regards
[...] Maven + (Spring + Hibernate) Annotation + MySql Example A simple project of using Spring and Hibernate (annotation version). [...]
what is the best way to wrap this up in a spring MVC web application?
thanks
Sorry, do not get you, mind to elaborate in detail?