Maven 2 + Hibernate 3.2 + MySQL Example (XML Mapping)

Note
This article is outdated, please refer to the latest Hibernate 3.6 tutorial at – Maven 3 + Hibernate 3.6 + Oracle 11g Example (XML Mapping).

This quick guide show you how to use Maven to generate a simple Java project, and uses Hibernate to insert a record into MySQL database.

Tools & technologies used in this article :

  1. Maven 2.2.1
  2. JDK 1.6.0_13
  3. Hibernate 3.2.3.GA
  4. MySQL 5.0

1. Table Creation

MySQL script to create a “stock” table.

DROP TABLE IF EXISTS `stock`;
CREATE TABLE `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 DEFAULT CHARSET=utf8;

2. Generate project structure with Maven

In command prompt, Issue “mvn archetype:generate“, choose project #15 to create a quick start Maven’s java project, then fill in your project’s information – groupId , artifactId and package.

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. Convert to Eclipse project

Issue “mvn eclipse:eclipse” to convert the newly generated project to Eclipse’s style project

4. Import converted project into Eclipse IDE

In Eclipse IDE, Choose File –> Import –> General folder, Existing Projects into Workspace –>Choose your project folder location. Done

5. Create a resources folder

Create a resources folder under “src/main” folder, “/src/main/resources” , later all the Hibernate’s xml files will put here. Maven will treat all files in this folder as resources files, and copy it to output classes automatically.

6. Review project structure

Make sure the folder structure as following

hibernate-example-1

Maven will generate all the Java’s standard folders structure for you (beside resources folder, quick start archetype #15 does not contains the resources folder)

7. Add Hibernate and MySQL dependency

Modify the Maven’s pom.xml file, add support for Hibernate and MySQL. Hibernate is required dom4j, commons-logging, commons-collections and cglib as dependency library, add it.

File : pom.xml

<project ...>
<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>
  <dependencies>
 
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </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>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>

Issue the “mvn eclipse:eclipse“, Maven will download all Hibernate and MySQL libraries automatically and put into Maven’s local repository. At the same time, Maven will add the downloaded libraries into Eclipse “.classpath” for dependency purpose. Like it again :) , no need to find the library and copy it myself.

8. Create Hibernate Mapping file + Model class

In prerequisite requirement , a table named “stock” is created, now you will need to create a Hibernate XML mapping file and model class for it.

Create a Stock.hbm.xml file and put it in “src/main/resources/com/mkyong/common/Stock.hbm.xml“. Create “resources/com/mkyong/common/” folder if it does not exists.

File : Stock.hbm.xml

<?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.common.Stock" table="stock" catalog="mkyong">
        <id name="stockId" type="java.lang.Integer">
            <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>

Create a Stock.java file and put it in “src/main/java/com/mkyong/common/Stock.java

File : Stock.java

package com.mkyong.common;
 
/**
 * Model class for Stock
 */
public class Stock implements java.io.Serializable {
 
	private static final long serialVersionUID = 1L;
 
	private Integer stockId;
	private String stockCode;
	private String stockName;
 
	public Stock() {
	}
 
	public Stock(String stockCode, String stockName) {
		this.stockCode = stockCode;
		this.stockName = stockName;
	}
 
	public Integer getStockId() {
		return this.stockId;
	}
 
	public void setStockId(Integer stockId) {
		this.stockId = stockId;
	}
 
	public String getStockCode() {
		return this.stockCode;
	}
 
	public void setStockCode(String stockCode) {
		this.stockCode = stockCode;
	}
 
	public String getStockName() {
		return this.stockName;
	}
 
	public void setStockName(String stockName) {
		this.stockName = stockName;
	}
 
}
Note
Create the model class and mapping files are quite tedious in large application, With Hibernate tools, this can be generate automatically, check this article – Hibernate tools to generate it automatically.

9. Create Hibernate Configuration file

Create a Hibernate’s configuration file and put under the resources root folder, “src/main/resources/hibernate.cfg.xml“. Fill in your MySQL setting accordingly.

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 resource="com/mkyong/common/Stock.hbm.xml"></mapping>
    </session-factory>
</hibernate-configuration>

Set the “show_sql” property to true will output the Hibernate SQL statement. Hibernate Dialect is telling your Hibernate application which SQL it has to generate to talk to your database. Please refer this article for other database dialect – Hibernate dialect collection.

10. Create Hibernate Utility class

Create a HibernateUtil.java class to take care of Hibernate start up and retrieve the session easily. Create a persistence folder and put this file in it, “src/main/java/com/mkyong/persistence/HibernateUtil.java

File : HibernateUtil.java

package com.mkyong.persistence;
 
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
 
public class HibernateUtil {
 
    private static final SessionFactory sessionFactory = buildSessionFactory();
 
    private static SessionFactory buildSessionFactory() {
        try {
            // Create the SessionFactory from hibernate.cfg.xml
            return new Configuration().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();
    }
 
}

11. Review project structure again

Sound like create many new files and folders, review it and make sure the folder structure as following

hibernate-example-2

12. Code it to save the record

Modify the default App.java class as following :

File : App.java

package com.mkyong.common;
 
import org.hibernate.Session;
import com.mkyong.persistence.HibernateUtil;
 
public class App 
{
    public static void main( String[] args )
    {
        System.out.println("Maven + Hibernate + MySQL");
        Session session = HibernateUtil.getSessionFactory().openSession();
 
        session.beginTransaction();
        Stock stock = new Stock();
 
        stock.setStockCode("4715");
        stock.setStockName("GENM");
 
        session.save(stock);
        session.getTransaction().commit();
    }
}

13. Run it and see output

Run your App.java, it will insert a new record into “Stock” table.

Maven + Hibernate + MySQL
...
Dec 17, 2009 5:05:26 PM org.hibernate.impl.SessionFactoryObjectFactory addInstance
INFO: Not binding factory to JNDI, no JNDI name configured
Hibernate: insert into mkyong.stock (STOCK_CODE, STOCK_NAME) values (?, ?)

Done.

Download it – Maven_Hibernate_MySQL_Example.zip (12kb)

Reference

  1. http://docs.jboss.org/hibernate/core/3.3/reference/en/html/tutorial.html
Tags :

About the Author

mkyong
Founder of Mkyong.com and HostingCompass.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

  • Pingback: watch movies online free()

  • Pingback: Learn More()

  • Pingback: Blue Coaster33()

  • Pingback: Google()

  • manas naik

    Hi,

    Yesterday I wrote one hiberanate program for curd operation as well as in JDBC also.But I am getting JDBC more faster than hibernate.So, why people says that hibernate is fister than JDBC.

  • Zenith

    Really very helpful. Thank you.

  • Shridharan

    What is the use of implementing java.io.serializable interface?
    Can’t we able to achieve the functionality without implementing serializable interface?

  • Iyappan

    Need to Change in pom.xml

    org.hibernate
    hibernate
    3.2.3.ga

    • Iyappan

      <dependency>
      <groupId>org.hibernate </groupId>
      <artifactId>hibernate </artifactId>
      <version>3.2.3.ga </version>
      </dependency>

  • Sam

    Please Help: I tried this example, got the error:

    Initial SessionFactory creation failed.org.hibernate.HibernateException: Unable to instantiate default tuplizer [org.hibernate.tuple.entity.PojoEntityTuplizer]
    Exception in thread “main” java.lang.ExceptionInInitializerError
    at com.mkyong.persistence.HibernateUtil.buildSessionFactory(HibernateUtil.java:18)
    at com.mkyong.persistence.HibernateUtil.(HibernateUtil.java:8)
    at com.mkyong.common.App.main(App.java:11)
    Caused by: org.hibernate.HibernateException: Unable to instantiate default tuplizer [org.hibernate.tuple.entity.PojoEntityTuplizer]
    at org.hibernate.tuple.entity.EntityTuplizerFactory.constructTuplizer(EntityTuplizerFactory.java:110)
    at org.hibernate.tuple.entity.EntityTuplizerFactory.constructDefaultTuplizer(EntityTuplizerFactory.java:135)
    at org.hibernate.tuple.entity.EntityEntityModeToTuplizerMapping.(EntityEntityModeToTuplizerMapping.java:56)
    at org.hibernate.tuple.entity.EntityMetamodel.(EntityMetamodel.java:323)
    at org.hibernate.persister.entity.AbstractEntityPersister.(AbstractEntityPersister.java:433)
    at org.hibernate.persister.entity.SingleTableEntityPersister.(SingleTableEntityPersister.java:109)
    at org.hibernate.persister.PersisterFactory.createClassPersister(PersisterFactory.java:55)
    at org.hibernate.impl.SessionFactoryImpl.(SessionFactoryImpl.java:231)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1313)
    at com.mkyong.persistence.HibernateUtil.buildSessionFactory(HibernateUtil.java:13)
    … 2 more
    Caused by: java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at org.hibernate.tuple.entity.EntityTuplizerFactory.constructTuplizer(EntityTuplizerFactory.java:107)
    … 11 more
    Caused by: java.lang.NoSuchMethodError: org.objectweb.asm.ClassWriter.(I)V
    at net.sf.cglib.core.DebuggingClassWriter.(DebuggingClassWriter.java:47)
    at net.sf.cglib.core.DefaultGeneratorStrategy.getClassWriter(DefaultGeneratorStrategy.java:30)
    at net.sf.cglib.core.DefaultGeneratorStrategy.generate(DefaultGeneratorStrategy.java:24)
    at net.sf.cglib.core.AbstractClassGenerator.create(AbstractClassGenerator.java:216)
    at net.sf.cglib.core.KeyFactory$Generator.create(KeyFactory.java:144)
    at net.sf.cglib.core.KeyFactory.create(KeyFactory.java:116)
    at net.sf.cglib.core.KeyFactory.create(KeyFactory.java:108)
    at net.sf.cglib.core.KeyFactory.create(KeyFactory.java:104)
    at net.sf.cglib.proxy.Enhancer.(Enhancer.java:69)
    at org.hibernate.proxy.pojo.cglib.CGLIBLazyInitializer.getProxyFactory(CGLIBLazyInitializer.java:117)
    at org.hibernate.proxy.pojo.cglib.CGLIBProxyFactory.postInstantiate(CGLIBProxyFactory.java:43)
    at org.hibernate.tuple.entity.PojoEntityTuplizer.buildProxyFactory(PojoEntityTuplizer.java:188)
    at org.hibernate.tuple.entity.AbstractEntityTuplizer.(AbstractEntityTuplizer.java:128)
    at org.hibernate.tuple.entity.PojoEntityTuplizer.(PojoEntityTuplizer.java:78)
    … 16 more

  • http://webhospitalize.com Fire Hose

    Thankfulness to my father who told me regarding this website, this
    website is really remarkable.

  • http://carrara-designs.be/information/chanel.html ____ ___

    It’s very effortless to find out any topic on net as compared to books, as I found this post at this web page.

  • Evanfa

    Hi
    This is an amazing tuto and really works.
    But I have a little question what about if I want to create a .jar file of this app?

    I tried to do it but doenst work, what is needed to do it? another kind of configuration to run in standalone mode?

    Please I need to know! xd
    Thanks a lot

  • Parbhat

    Hi,Thanks for making the thing simple for us.Your example are really useful to learn.I learnt Spring only from your example.Thanks a lot.Now i started Hibernate.I was trying with the first example and i am gettinh the below exception.Can you plz help me to sort it …

    Initial SessionFactory creation failed.java.lang.NoClassDefFoundError: org/dom4j/DocumentException
    Exception in thread “main” java.lang.ExceptionInInitializerError
    at com.mukesh.hibernate.testing.HibernateTest.HibernateUtil.buildSessionFactory(HibernateUtil.java:17)
    at com.mukesh.hibernate.testing.HibernateTest.HibernateUtil.(HibernateUtil.java:8)
    at com.mukesh.hibernate.testing.HibernateTest.App.main(App.java:12)
    Caused by: java.lang.NoClassDefFoundError: org/dom4j/DocumentException
    at com.mukesh.hibernate.testing.HibernateTest.HibernateUtil.buildSessionFactory(HibernateUtil.java:13)
    … 2 more
    Caused by: java.lang.ClassNotFoundException: org.dom4j.DocumentException
    at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
    … 3 more

  • Bhargav Pandya

    How to solve
    org.hibernate.PropertyValueException: not-null property references a null or transient value

  • Kavin

    How to perform CRUD operation in Hibernate of netbeans7.0. pls give examples

  • http://monicasbroadcasting.shutterfly.com/ useful site

    Fastidious response in return of this issue with firm arguments and explaining
    all concerning that.

  • Pavan

    Exception in thread “main” java.lang.ExceptionInInitializerError
    at com.example.chapter01.EventClient.main(EventClient.java:18)
    Caused by: org.hibernate.HibernateException: /hibernate.cfg.xml not found
    at org.hibernate.util.ConfigHelper.getResourceAsStream(ConfigHelper.java:170)
    at org.hibernate.cfg.Configuration.getConfigurationInputStream(Configuration.java:1439)
    at org.hibernate.cfg.Configuration.configure(Configuration.java:1461)
    at org.hibernate.cfg.Configuration.configure(Configuration.java:1448)
    at com.example.chapter01.HibernateUtil.buildSessionFactory(HibernateUtil.java:12)
    at com.example.chapter01.HibernateUtil.(HibernateUtil.java:8)
    … 1 more

    • yingzhang

      you can change the path of hibernate.cfg.xml

      because when you run the program the Relative path of the project has changed?

    • http://www.javaaster.com Tarun

      new Configuration().configure().buildSessionFactory();

  • http://www.haotwo.com houchenxi

    This is an example that actually works.
    Btw, mkyong, I’m curious about your ethnic background, were you a Chinese citizen born somewhere in China?

  • snowdream

    At the step 13,how to run the application??

    • snowdream

      I got it ,Thank you.

  • EnSomHodder

    From my humble opinion, most maven dependencies are not necessary, for your examples, “hibernate core” and “mysql-connector” dependency are sufficient. Anyway, your tutorial is easy to follow, thank you very much!

  • Josue

    Great Hibernate Tutorial straight to the point super helpful!

  • bizkit

    I am getting a “hibernate.cfg.xml” not found exception. Have tried all the possible solutions available on the net. Any idea why this might be happening…

    • http://www.mkyong.com mkyong

      Make sure hibernate.cfg.xml in your project classpath.

      • bizkit

        Hi,

        Thank You for your reply ;-)
        I Solved the problem. But I had to load the file from the Hibernate util by creating a file object and providing the physical path of the file on the machine. Any idea why this might be needed? I think there is some issue with eclipse (not sure though).

  • zahra

    hi,
    I exactly do what you say in steps
    but I have problem with some of the import,
    this error:
    “the import org.hibernate can not be resolved”
    what should I do?
    please help
    thanks a lot

    • Seitan

      Zahra I got the same error I did this and fix it:
      add to pom:

      &lt;dependency&gt;
      	&lt;groupId&gt;org.hibernate&lt;/groupId&gt;
      	&lt;artifactId&gt;hibernate-core&lt;/artifactId&gt;
      	&lt;version&gt;3.6.3.Final&lt;/version&gt;
      &lt;/dependency&gt;

      :)

      • ANAS

        I got the some problem.
        Thank you for the replay ;)

  • http://android9patch.blogspot.com Richard

    On step 3, don’t forget to do:
    cd HibernateExample

    :)

  • http://hi2lanka.com Arun

    Hi Guys, I am not able to use the maven , it doesnt work for me. when i say eclipse:eclipse it fails with one jar file. badly need your help

    • http://www.mkyong.com mkyong

      What errors prompt in console?

      • http://hi2lanka.com Arun

        I got it working buddy, thanks alot. your articles are superb

  • Jani

    SLF4J: Failed to load class “org.slf4j.impl.StaticLoggerBinder”.
    SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
    Initial SessionFactory creation failed.java.lang.NoClassDefFoundError: org/slf4j/impl/StaticLoggerBinder
    Exception in thread “main” java.lang.ExceptionInInitializerError
    at com.mkyong.persistence.HibernateUtil.buildSessionFactory(HibernateUtil.java:20)
    at com.mkyong.persistence.HibernateUtil.(HibernateUtil.java:10)
    at com.mkyong.common.App.main(App.java:17)
    Caused by: java.lang.NoClassDefFoundError: org/slf4j/impl/StaticLoggerBinder
    at org.slf4j.LoggerFactory.getSingleton(LoggerFactory.java:223)
    at org.slf4j.LoggerFactory.bind(LoggerFactory.java:120)
    at org.slf4j.LoggerFactory.performInitialization(LoggerFactory.java:111)
    at org.slf4j.LoggerFactory.getILoggerFactory(LoggerFactory.java:269)
    at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:242)
    at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:255)
    at org.hibernate.cfg.Configuration.(Configuration.java:152)
    at com.mkyong.persistence.HibernateUtil.buildSessionFactory(HibernateUtil.java:15)
    … 2 more
    Caused by: java.lang.ClassNotFoundException: org.slf4j.impl.StaticLoggerBinder
    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)
    at java.lang.ClassLoader.loadClassInternal(Unknown Source)
    … 10 more

  • Srikanth Jessu

    If you are using Maven then use this dependenices in your POM.xml.

     
        <!-- My database engine is H2 -->
     
        	com.h2database
        	h2
        	1.3.155
        	jar
        	compile
     
     
        <!-- Hibernate dependencies-->
     
        	org.hibernate
        	hibernate-core
        	3.6.4.Final
        	jar
        	compile    	
     
     
     
        	javassist
        	javassist
        	3.12.1.GA
        	jar
        	compile
     
     
        <!-- configure logback.xml to get logs -->
     
        	ch.qos.logback
        	logback-classic
        	0.9.28
        	jar
        	compile
  • Arby

    Stupid question number one. And this is Maven question not Hibernate (hint, hint, hint, please create Tutorial for Maven, hehehe)

    From which directory do I run mvn eclipse:eclipse command. I’m assuming I run it from with the PROJECT DIRECTORY since command is operating on the Project.

    Second, Once I “Eclipsify” the Maven Project and have imported it into Eclipse, AND then I have to change pom.xml to add additional dependencies, if I go and run mvn eclipse:eclipse again, I will have to refresh Project Folder inside Eclipse. Is there easy way to execute mvn from inside Eclipse?

    • http://www.mkyong.com mkyong

      1. Run where the pom.xml reside.

      2. Eclipse IDE –> Run –> External Tool, put your maven command here. Later you can run mvn command inside Eclipse IDE.

      Will provides more Maven examples in future. Thanks for suggestions.

      • Arby

        Doh! Thank you!

  • http://sagerbe.org Jim

    Hi,

    Nice site. Very informative.

    I’m trying to run the Hibernate example but I get:


    [WARNING] An error occurred during dependency resolution.
    Failed to retrieve com.vaadin:vaadin-6.1-SNAPSHOT
    Caused by: Could not find artifact com.vaadin:vaadin:jar:6.1-SNAPSHOT

    Try downloading the file manually from the project website.

    When I look on the vaadin site they don’t have version 6.1 – only 6.4.x – is it okay to modify the version number in pom.xml to use the later/est version?

    • http://sagerbe.org Jim

      This is at step 6 of the tutorial but I should probably first try to resolve an earlier problem: something I noticed at step 5 is that the project structure I get is different to the one shown in the image. For example I don’t get a test directory at all. And under ‘src/main/java’ I get ColorPicker code instead of App, Stock etc.

      Can you tell me why this is?

      Thanks.

      • http://sagerbe.org Jim

        Okay, it appears the java quickstart archetype is now 99, not 15.

        • http://www.mkyong.com mkyong

          Thanks for the update, may be i’m using old Maven v 2.x, it’s now v3.0, do not have time to research on it yet :p

  • carldeltoro

    soy de Venezuela,me ayudaste un mundo con este ejemplo…los otros que había consultado no funcionaban mil gracias!!!!

    I’m from Venezuela, helped me a world with this example … the other that she had not worked .many thanks!!

  • aaronhuang

    Changes
    ————————————-
    1. Hibernate maven repository change to jboss ,please add follow in pom.xml

    <repositories>
    <repository>
    <id>JBoss</id>
    <name>JBoss Repsitory</name>
    <layout>default</layout>
    <url>http://repository.jboss.org/maven2</url&gt;
    </repository>
    </repositories>
    2. Add jta class dependency

    javax.transaction
    jta
    1.1
    compile

    Hope this helpful

    • http://www.mkyong.com mkyong

      Thanks for sharing your find out.

    • Tsvetan Vasilev

      Great, It works! Thank you all for the help :)

  • aaronhuang

    Changes
    ————————————-
    1. Hibernate maven repository change to jboss ,please add follow in pom.xml

    JBoss
    JBoss Repsitory
    default
    http://repository.jboss.org/maven2

    2. Add jta class dependency

    javax.transaction
    jta
    1.1
    compile

    Hope this helpful

  • Mite

    I love your website. It has helped me several times so far.
    Right now I have this problem. I use MySQL and hibernate with java. After a while i get these exceptions:
    java.io.EOFException: Can not read response from server. Expected to read 4 bytes, read 0 bytes

    com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure

    I know it is a common problem on the web but I haven’t found the solution.
    Can anyone help me with this?

    Thank you

    • http://www.mkyong.com mkyong

      A bit hard to say what caused it by looking at few lines of code, do you see any “caused by” exception in your log? and which line of code caused the error?

  • vijay

    am getting this as output in eclipse console , help me out

    Maven + Hibernate + MySQL

    Exception in thread "main" java.lang.NoClassDefFoundError: javax/transaction/Synchronization
    	...
    Caused by: java.lang.ClassNotFoundException: javax.transaction.Synchronization
    	at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
    	at java.security.AccessController.doPrivileged(Native Method)
    	at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
    	at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
    	at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
    	at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
    	... 5 more
    • http://www.mkyong.com mkyong
      • vijay

        when i give mvn eclipse:clean eclipse:eclipse in command line ..
        am getting a message like this ..

        Please run the same goal with the -DdownloadSources=true parameter in order to check remote repositories for sources.

        • http://www.mkyong.com mkyong

          not a big deal, just ignore it if you dun want to attach the source.

          • vijay

            still am getting errors , so i thought this might be related to it ..
            the exception error message is …

            Caused by: java.lang.ClassNotFoundException: javax.transaction.Synchronization
            	at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
            	at java.security.AccessController.doPrivileged(Native Method)
            	at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
            	at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
            	at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
            	at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
            	... 5 more
          • http://www.mkyong.com mkyong

            Obviously…library is missing, For Eclipse IDE, make sure it’s in your Eclipse server plugin’s deployment folder.

            http://www.mkyong.com/maven/maven-dependency-libraries-not-deploy-in-eclipse-ide/

          • vijay

            please give me the updated pom.xml file ..

            and also suggest some more tutorials for me to learn hibernate using maven convention in eclipse IDE

          • http://www.mkyong.com mkyong

            Nothing to do with the pom.xml, make sure the libraries are all in your project dependency project.

          • vijay

            itz not working , i even downloaded that jta.jar and i included it manually in the classpath ,

          • hoganc

            Hi Vijay,

            I met the same problem with you. But try these may help you out (basically, rebuild your project for Eclipse):
            1. under HibernateExample folder: mvn clean
            2. mvn install
            3. mvn -Declipse.workspace= eclipse:configure-workspace
            4. mvn eclipse:clean
            5. mvn eclipse:eclipse

  • Roberto

    How to run the project on eclipse?
    I can only run the project by deploy the project on tomcat manager

    • http://www.mkyong.com mkyong

      Just import it into Eclipse IDE, and compile with “maven eclipse:eclipse” will do.

  • mlorenz1

    It looks like the jta dependency is now required. I verified this using my own project (slightly different from yours), then tried again with the project .zip file listed on this page. If you try to run the app, you’ll get something like this:

    [ERROR] BUILD ERROR
    [INFO] ————————————————————————
    [INFO] An exception occured while executing the Java class. null

    javax.transaction.Synchronization

    To fix it, I added the following to the pom.xml:

    javax.transaction
    jta
    1.1
    jar
    compile

    Otherwise, thanks for a very helpful tutorial!

    • http://www.mkyong.com mkyong

      Thanks for your tips.

  • java programmer

    I am just learning maven, and thought to try out your tutorial. I had a problem with hibernate, since there does not seem to be a hibernate3 directory (artifactID) or 3.2.3.GA (version).

    I tried finding alternatives, but then it couldn’t find source files for this and for asm.

  • Pingback: Hibernate Tutorials | Tutorials()

  • http://www.kaitrade.com John

    Very useful for a quick introduction – thanks

  • Pingback: Maven + Hibernate Annonation + MySQL Example | Hibernate()

  • http://night-fairy-tales.blogspot.com/ SMiGL

    simple, but useful