Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

An introduction about Hibernate in Java

This article will discuss about hibernate and also discuss a simple application using it.

Today, we are going to discuss about hibernate. We will also discuss a simple application using hibernate.

Introduction (Hibernate)

Hibernate allows you to map your Java classes to Database Table. We may define it as library, which provide a framework for mapping object oriented model to relational database. The best thing about hibernate is that it is a free software which is distributed under GNU Lesser General Public License.

Features :

  1. It allows you to map your classes to your database tables
  2. It provide facility for data retrieval
  3. All database details can be written in the configuration file.
  4. Cascading operation can be defined easily in the class file which ensure integrity in database
  5. Hql(Hibernate query language is provided by hibernate which can perform database operations through hibernate data object
  6. Development time reduces too much
  7. It supports automatic generation of primary key.
  8. Resultset are mapped into Java objects, which makes the processing part easier

A simple example for hibernate

First we will define the Author class which we map to database table.

Listing 1: Author class

package model;

import javax.persistence.Entity;
import javax.persistence.Id;

/**
 *
 * @author Anurag
 */
@Entity
public class Author {

    @Id
    private int id;
    private String name;
    private String location;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getLocation() {
        return location;
    }

    public void setLocation(String location) {
        this.location = location;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
} 
  1. We defined the class named Author
  2. This class has three fields which are id,name and location
  3. We have defined the setter and getter function for this fields

Now we define the configuration file which is hibernate.cfg.xml

Listing 2: 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.dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernatetutorial</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">csanurag</property>
        <property name="hibernate.hbm2ddl.auto">update</property>
        <property name="hibernate.current_session_context_class">thread</property>
        <mapping class="model.Author"/>
    </session-factory>
</hibernate-configuration> 

We are setting the properties for our database as well as mapping inside this configuration file. This is described more below :

  1. hibernate.dialect : We gave the dialect to be MYSQL to tell hibernate that we are going to connect to Mysql database using hibernate.
  2. hibernate.connection.driver_class : It is used to define the driver class we are going to use. We included the mysql driver class
  3. hibernate.connection.url : We define the connection string here.
  4. hibernate.connection.username : Here you define the username for mysql.
  5. hibernate.connection.password : Here you define the password for mysql.
  6. hibernate.hbm2ddl.auto : Automatically validates or exports schema DDL to the database when the SessionFactory is created.
  7. hibernate.current_session_context_class : The current context is thread. Session factory binds the session with the current context.
  8. mapping class : This is used to map the class(Author in this case) with database table.

Now we define a class which will help us obtain the Session Factory object.

Listing 3: Utility class (for obtaining session factory)

package Main;

/**
 *
 * @author Anurag
 */
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

public class Utility {

    private static final SessionFactory sessionFactory;

    static {
        try {
            sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
        } catch (Throwable ex) {

            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
} 
  1. We have made a object for session factory
  2. The method new AnnotationConfiguration().configure().buildSessionFactory(); is used to obtain the current session factory. This session factory object would be used to obtain a session
  3. We define a method getSessionFactory() which will return the session factory object

Lastly, we define the class to use this information and map this to database table.

Listing 4: App class

package Main;

/**
 *
 * @author Anurag
 */
import model.Author;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

public class App {

    public static void main(String args[]) {

        SessionFactory sf = Utility.getSessionFactory();
        Session s = sf.getCurrentSession();
        Transaction tx = s.beginTransaction();
        Author a = new Author();
        a.setId(1);
        a.setName("Anurag");
        a.setLocation("India");
        s.save(a);
        tx.commit();
    }
} 
  1. We obtain a session factory object using the Utility class we defined earlier
  2. We obtain a session object using the session factory object we just created
  3. Now we begin the transaction and store a transaction object.
  4. We make a Author class object and initialize its field with the data which we want to insert into database.
  5. After this we save the session by using the session.save object.We pass the object which we want to associate with this session.
  6. We commit the transaction so that to make the changes in database. This need to be done

Today we have learned on making a simple application in hibernate. We will learn about mappings in coming articles. See you next time.



My main area of specialization is Java and J2EE. I have worked on many international projects like Recorders,Websites,Crawlers etc.Also i am an Oracle Certified java professional as well as DB2 certified

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login