Hibernate Hello World (XML Mapping)

In this tutorial, we will see how to use Hibernate to map a Java class to database table and insert a new record into that table.

We will use MySQL database.


1. Technologies used

  • Hibernate 4.3.6.Final
  • MySQL 5.1
  • Maven 3.0.5
  • Eclipse 4.2
  • JDK 1.7


2. Create table : CUSTOMER

We use the following script to create CUSTOMER table.


3. Project structure

We create a Maven based Java application.



4. Project dependencies

We need Hibernate and MySQL connector dependencies.


5. Model class

It is a simple JavaBean class whose instance will be stored in the CUSTOMER table.

File : src/main/java/com/keylesson/persistence/Customer.java


6. Mapping file

It is an XML document where we define how the model class (Customer) will be mapped to the database table (CUSTOMER).

In other words, we tell Hibernate what table in the database to access and what columns in that table to use for the model class.

File : src/main/resources/com/keylesson/persistence/Customer.hbm.xml


7. Hibernate configuration file

It is used to configure Hibernate by adding connection parameters and the mapping file.

File : src/main/resources/hibernate.cfg.xml


8. Hibernate Utility

We will use it to startup Hibernate and obtain the session instance.


9. Test It


Output :

Hibernate: insert into CUSTOMER (NAME, ADDRESS, CREATION_DATE) values (?, ?, ?)


Download source code



  • tarik

    Salut ,

    j’ai crée un projet web avec maven , mais eclipse il ne connu pas les lib de hibernate .


    • walid

      Il faut créer un projet java standard : maven-archetype-quickstart
      Exemple : [mvn archetype:generate -DgroupId=com.keylesson.hibernate -DartifactId=Hibernate-Hello-World-XML -DarchetypeArtifactId=maven-archetype-quickstart]

      Et après l’avoir importé dans Eclipse il faut exécuter la commande [mvn clean install eclipse:clean eclipse:eclipse]
      pour clean and install et en même temps adapter le projet à Eclipse.