Maven 2 + Hibernate 3.2 + MySQL Example (Annotation)
This article is outdated, and some information is no longer valid in latest Hibernate development. You should refer to this latest – Maven 3 + Hibernate 3.6.3 + Oracle 11g Example (Annotation) tutorial.
This tutorial will modify the previous Maven 2 + Hibernate 3.2 + MySQL Example (XML mapping), and replace the Hibernate XML mapping file with Annotation code.
Tools & technologies used in this article :
- Maven 2.2.1
- JDK 1.6.0_13
- Hibernate 3.2.3.GA
- MySQL 5.0
1. Create project infrastructure
Create project infrastructure in Maven + Hibernate (XML mapping file) + MySQL Example
2. Add JBoss repository
JBoss repository in pom.xml is required to download the Hibernate annotation library.
<repositories> <repository> <id>JBoss repository</id> <url>http://repository.jboss.com/maven2/</url> </repository> </repositories>
3. Add Hibernate annotation dependency
Add hibernate-annotations and hibernate-commons-annotations dependency in pom.xml.
<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>
File : pom.xml
<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>HibernateExample</artifactId> <packaging>jar</packaging> <version>1.0-SNAPSHOT</version> <name>HibernateExample</name> <url>http://maven.apache.org</url> <repositories> <repository> <id>JBoss repository</id> <url>http://repository.jboss.com/maven2/</url> </repository> </repositories> <dependencies> <!-- MySQL database driver --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.9</version> </dependency> <!-- Hibernate core --> <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>cglib</groupId> <artifactId>cglib</artifactId> <version>2.2</version> </dependency> <!-- Hibernate library dependecy end --> <dependency> <groupId>javax.transaction</groupId> <artifactId>jta</artifactId> <version>1.1</version> </dependency> </dependencies> </project>
4. Update project classpath
Issue “mvn eclipse:eclipse” in command prompt to download the dependency library and update the Eclipse’s project classpath.
5. Update HibernateUtil.java
Update “HibernateUtil” to use “AnnotationConfiguration” instead of “Configuration” to build the Hibernate session factory.
Previously is using “Configuration” – For Hibernate XML mapping file
return new Configuration().configure().buildSessionFactory();
Change it to “AnnotationConfiguration” – For Hibernation annotation support
return new AnnotationConfiguration().configure().buildSessionFactory();
File : HibernateUtil.java
package com.mkyong.persistence; import org.hibernate.SessionFactory; import org.hibernate.cfg.AnnotationConfiguration; public class HibernateUtil { private static final SessionFactory sessionFactory = buildSessionFactory(); private static SessionFactory buildSessionFactory() { try { // Create the SessionFactory from hibernate.cfg.xml return new AnnotationConfiguration().configure().buildSessionFactory(); } catch (Throwable ex) { // Make sure you log the exception, as it might be swallowed System.err.println("Initial SessionFactory creation failed." + ex); throw new ExceptionInInitializerError(ex); } } public static SessionFactory getSessionFactory() { return sessionFactory; } public static void shutdown() { // Close caches and connection pools getSessionFactory().close(); } }
6. Update Model class
Update “Stock.java” to use annotation as follow :
Stock.java
package com.mkyong.common; 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; } }
7. Delete existing Hibernate XML mapping file
Delete existing Hibernate XML mapping file – “Stock.hbm.xml”, this is no longer require.
8. Update Hibernate configuration file
Update the Hibernate configuration file – hibernate.cfg.xml.
Previously it had the Hibernate XML mapping file with “mapping resource” tag
<mapping resource="com/mkyong/common/Stock.hbm.xml"></mapping>Change it to model class with “mapping class” tag
<mapping class="com.mkyong.common.Stock"></mapping>File : hibernate.cfg.xml
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <property name="hibernate.bytecode.use_reflection_optimizer">false</property> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <property name="hibernate.connection.password">password</property> <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/mkyong</property> <property name="hibernate.connection.username">root</property> <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> <property name="show_sql">true</property> <mapping class="com.mkyong.common.Stock"></mapping> </session-factory> </hibernate-configuration>
9. Review project structure
Sound like few files were modified, review it and make sure the folder structure as follow :

10. Run it and see output
Run your App.java, it will insert a new record into “Stock” table. The result should be same with previous Hibernate XML mapping file example.
Maven + Hibernate + MySQL ... Hibernate: insert into mkyong.stock (STOCK_CODE, STOCK_NAME) values (?, ?)
Done.
should hibernate-commons-annotations
be org.hibernate
?
i mean this one
It is valid in old Hibernate 3.2.3. In Hibernate 3.6, it’s integrated into the core module.
nice job, like it!
I can not figure out how to fix this problem:INFO: Not binding factory to JNDI, no JNDI name configured
here is the output:
Maven + Hibernate + MySQL
Jan 29, 2011 7:10:52 PM org.hibernate.cfg.annotations.Version
INFO: Hibernate Annotations 3.3.0.GA
Jan 29, 2011 7:10:52 PM org.hibernate.cfg.Environment
INFO: Hibernate 3.2.3
Jan 29, 2011 7:10:52 PM org.hibernate.cfg.Environment
INFO: hibernate.properties not found
Jan 29, 2011 7:10:52 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: Bytecode provider name : cglib
Jan 29, 2011 7:10:52 PM org.hibernate.cfg.Environment
INFO: using JDK 1.4 java.sql.Timestamp handling
Jan 29, 2011 7:10:52 PM org.hibernate.cfg.Configuration configure
INFO: configuring from resource: /hibernate.cfg.xml
Jan 29, 2011 7:10:52 PM org.hibernate.cfg.Configuration getConfigurationInputStream
INFO: Configuration resource: /hibernate.cfg.xml
Jan 29, 2011 7:10:52 PM org.hibernate.cfg.Configuration doConfigure
INFO: Configured SessionFactory: null
Jan 29, 2011 7:10:52 PM org.hibernate.cfg.AnnotationConfiguration secondPassCompile
INFO: Hibernate Validator not found: ignoring
Jan 29, 2011 7:10:52 PM org.hibernate.connection.DriverManagerConnectionProvider configure
INFO: Using Hibernate built-in connection pool (not for production use!)
Jan 29, 2011 7:10:52 PM org.hibernate.connection.DriverManagerConnectionProvider configure
INFO: Hibernate connection pool size: 20
Jan 29, 2011 7:10:52 PM org.hibernate.connection.DriverManagerConnectionProvider configure
INFO: autocommit mode: false
Jan 29, 2011 7:10:52 PM org.hibernate.connection.DriverManagerConnectionProvider configure
INFO: using driver: com.mysql.jdbc.Driver at URL: jdbc:mysql://localhost:3306/mkyong
Jan 29, 2011 7:10:52 PM org.hibernate.connection.DriverManagerConnectionProvider configure
INFO: connection properties: {user=root, password=****}
Jan 29, 2011 7:10:53 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: RDBMS: MySQL, version: 5.5.8
Jan 29, 2011 7:10:53 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: JDBC driver: MySQL-AB JDBC Driver, version: mysql-connector-java-5.1.9 ( Revision: ${svn.Revision} )
Jan 29, 2011 7:10:53 PM org.hibernate.dialect.Dialect
INFO: Using dialect: org.hibernate.dialect.MySQLDialect
Jan 29, 2011 7:10:53 PM org.hibernate.transaction.TransactionFactoryFactory buildTransactionFactory
INFO: Using default transaction strategy (direct JDBC transactions)
Jan 29, 2011 7:10:53 PM org.hibernate.transaction.TransactionManagerLookupFactory getTransactionManagerLookup
INFO: No TransactionManagerLookup configured (in JTA environment, use of read-write or transactional second-level cache is not recommended)
Jan 29, 2011 7:10:53 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Automatic flush during beforeCompletion(): disabled
Jan 29, 2011 7:10:53 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Automatic session close at end of transaction: disabled
Jan 29, 2011 7:10:53 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: JDBC batch size: 15
Jan 29, 2011 7:10:53 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: JDBC batch updates for versioned data: disabled
Jan 29, 2011 7:10:53 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Scrollable result sets: enabled
Jan 29, 2011 7:10:53 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: JDBC3 getGeneratedKeys(): enabled
Jan 29, 2011 7:10:53 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Connection release mode: auto
Jan 29, 2011 7:10:53 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Maximum outer join fetch depth: 2
Jan 29, 2011 7:10:53 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Default batch fetch size: 1
Jan 29, 2011 7:10:53 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Generate SQL with comments: disabled
Jan 29, 2011 7:10:53 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Order SQL updates by primary key: disabled
Jan 29, 2011 7:10:53 PM org.hibernate.cfg.SettingsFactory createQueryTranslatorFactory
INFO: Query translator: org.hibernate.hql.ast.ASTQueryTranslatorFactory
Jan 29, 2011 7:10:53 PM org.hibernate.hql.ast.ASTQueryTranslatorFactory
INFO: Using ASTQueryTranslatorFactory
Jan 29, 2011 7:10:53 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Query language substitutions: {}
Jan 29, 2011 7:10:53 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: JPA-QL strict compliance: disabled
Jan 29, 2011 7:10:53 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Second-level cache: enabled
Jan 29, 2011 7:10:53 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Query cache: disabled
Jan 29, 2011 7:10:53 PM org.hibernate.cfg.SettingsFactory createCacheProvider
INFO: Cache provider: org.hibernate.cache.NoCacheProvider
Jan 29, 2011 7:10:53 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Optimize cache for minimal puts: disabled
Jan 29, 2011 7:10:53 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Structured second-level cache entries: disabled
Jan 29, 2011 7:10:53 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Echoing all SQL to stdout
Jan 29, 2011 7:10:53 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Statistics: disabled
Jan 29, 2011 7:10:53 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Deleted entity synthetic identifier rollback: disabled
Jan 29, 2011 7:10:53 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Default entity-mode: pojo
Jan 29, 2011 7:10:53 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Named query checking : enabled
Jan 29, 2011 7:10:53 PM org.hibernate.impl.SessionFactoryImpl
INFO: building session factory
Jan 29, 2011 7:10:53 PM org.hibernate.impl.SessionFactoryObjectFactory addInstance
INFO: Not binding factory to JNDI, no JNDI name configured
k, got this figured out.
in App.java, I was missing: session.save(stock);
Thanks for this website.
The import org.hibernate.cfg.AnnotationConfiguration cannot be resolved ..what it’s that???
i had Add the dependency in Maven’s pom.xml!!!!!
Obviously, it’s from Hibernate annotation library
, double check your Hibernate version or download this project and compare it with yours.
Hi,
When i try to run the project example in Eclipse Helios, the Stock.java class has some errors like:
- The attribute uniqueConstraints is undefined for the annotation type Table
- The attribute name is undefined for the annotation type Table
- The annotation @Table must define the attribute appliesTo
- The attribute catalog is undefined for the annotation type Table
You can help me about this?
Thanks.
Regards,
MiguelMac
@Table is belong to standard JPA javax.persistence.Table , you may be using old j2ee version, try upgrade to 1.5
How can i upgrade to 1.5? It’s with maven?
Thanks.
Regards,
MiguelMac
you need javaee.jar , from your j2ee SDK library folder.
Add this in pom,
javax.persistence
persistence-api
1.0
hello i got a problema when run the java app
INFO: building session factory
Initial SessionFactory creation failed.java.lang.NoSuchMethodError: org.objectweb.asm.ClassWriter.(I)V
Exception in thread “main” java.lang.ExceptionInInitializerError
i don’t know what it is ??
See here
http://www.mkyong.com/hibernate/java-lang-nosuchmethoderror-org-objectweb-asm-classwriter/
Hello, this is nice straightforward Wicket/Hibernate tutorial but it went South on me later this day. Exception snippet follows:
Exception in thread “main” java.lang.ExceptionInInitializerError
at com.mkyong.persistence.HibernateUtil.buildSessionFactory(HibernateUtil.java:18)
at com.mkyong.persistence.HibernateUtil.(HibernateUtil.java:8)
This is not a wicket example, it’s a hibernate annotation hello world project, it will be better if you can send me your project via email.
very easy to understand !
Thanks a lot.
[...] Maven + Hibernate Annotation + MySQL Example A quick start to create a project with Maven, Hibernate (Annotation) and MySQL. [...]