Tuesday 21 January 2014

Basic Hibernate Application in Eclipse



This tutorial demonstrates how to use Hibernate which is an Object relational mapping tool for Java platform.
This is a simple example of creating an object in Java and mapping it to a table in mysql database. (inserting rows into the mysql database using Hibernate)


Before we start with the application we need the following:

Step 1: Create a Java project in Eclipse.



Step 2: Provide a name for your project and click on ‘Finish’



Step 3: Add the following jars (which are present in the downloaded hibernate x.x -> lib -> required folder)  and also the downloaded mysql odbc jar file to the project by right clicking on the project name followed by Properties ->Java Build Path -> Libraries -> Add External jars



Step 4: Create the hibernate.cfg.xml file in the src folder of the project and copy the following code into the xml file:



Step 5: Update the hibernate.cfg.xml file parameters ( port number, database name, username password). The final hibernate.cfg.xml should look as follows:


Step 6: Create a package ‘com.model’ and create two classes named ‘Employee’ and ‘HibernateMain’ within that package and paste the following codes in the respective class files:

Employee.java


Hibernate.java


Step 7 : Your final directory structure should look as follows:


Step 8: Run the HibernateMain.java as a Java Application.  The console should show your insert queries as follows:



If you open mysql and check the database, the two employee rows should be present.



Notes:
  • The Annotations in the Employee.java file help Hibernate decide the structure of the table to be created in the database. For example, @Entity tells Hibernate to treat this object as a table in the database. @Id annotation just above the declaration of parameter eid in the Employee.java file tells Hibernate to treat eid as the primary key of the table. @Table (name="employee") decides the name of the table which will be created in the database. 
  • For every new model class for which we need to create a table we need to give the @Entity annotation in the class file itself and add the mapping parameter in the hibernate.cfg.xml file as <mapping class="com.model.class_name"/>
  • The <property name="hibernate.hbm2ddl.auto">create</property>
    which is set to create in our example automatically creates a schema destroying the previous data
    The list of possible values for this parameter are,
    1. validate: validate the schema, makes no changes to the database.
    2. update: update the schema.
    3. create: creates the schema, destroying previous data.
    4. create-drop: drop the schema at the end of the session.



No comments:

Post a Comment