First Hibernate Application using Annotation

Lets we start on this topics. First we will see what is the process of using database without using Hibernate.
Saving Without Hibernate ->
  • JDBC Database configuration
  • The Model Object
  • Service method to create the model object
  • Database Design 
  • DAO method to use saving the model object to the database using SQL queries.
With Hibernate Way->
  • JDBC Database Configuration  ->  Hibernate Configuration
  • The Model Object   -> Using Annotation
  • Service method to create the model object -> Using the Hibernate API
  • Database Design   -> Not Needed
  • DAO method to use saving the model object to the database using SQL queries -> Not needed
Now as above steps of using hibernate, firstly we have to create Hibernate Configuration file.

Step 1: File Name -> hibernate.cfg.xml in src folder of the application


Now we need to type all the detail related to MySQL database so we can use in our application.
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>
        <!– Database connection settings –>
         <property name=”connection.driver_class”>com.mysql.jdbc.Driver</property>
         <property name=”connection.url”>jdbc:mysql://localhost:3306/hibernateDB</property>
         <property name=”connection.username”>username</property>
         <property name=”connection.password”>password</property>
         <property name=”connection.pool_size”>1</property>
         <!– SQL dialect –>
         <property name=”dialect”>org.hibernate.dialect.MySQLDialect</property>

        <!– Enable Hibernate’s automatic session context management –>
          <property name=”current_session_context_class”>thread</property>
       
        <!– Disable the second-level cache –>
         <property name=”cache.provider_class”>org.hibernate.cache.NoCacheProvider</property>

        <!– Show all executed SQL to stdout –>
         <property name=”show_sql”>true</property>
       
        <!– Drop and re-create the database schema on startup –>
         <property name=”hbm2ddl.auto”>create</property>
        
          <mapping class=”com.sdnext.hibernate.tutorial.dto.UserDetails”/>
                 
     </session-factory>
 </hibernate-configuration>

Here below property configure  driver of the specific database

<property name=”connection.driver_class”>com.mysql.jdbc.Driver</property>

Next line we configure the Database connection url
suppose we want to connect the database name hibernateDB 

<property name=”connection.url”>jdbc:mysql://localhost:3306/hibernateDB</property>

Next two lines set the user name and password of the connecting database hibernateDB

 <property name=”connection.username”>username</property>
 <property name=”connection.password”>password</property> 

Next line configure Dialect of the database MySQL, every database has its own Dialect.
What is Dialect? means Dialect is configuration specify here so hibernate knows whats kind of language we are used and what type database we are used. we can say it is database dependent. It connects the database specific query language which we want to use.

<property name=”dialect”>org.hibernate.dialect.MySQLDialect</property> 
  
The below line configured the model class name UserDetails its object we want save on the database hibernateDB
<mapping class=”com.sdnext.hibernate.tutorial.dto.UserDetails”/>

Now step 1 is over now we move to another step Now we have to create a Model class  

Step 2: UserDetails.java

package com.sdnext.hibernate.tutorial.dto;
import java.util.Date;
 

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

@Entity
public class UserDetails
{
    @Id
    private int    userId;
    private String userName;
    public int getUserId() {
        return userId;
    }
    public void setUserId(int userId) {
        this.userId = userId;
    }
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
}
Here @Entity means it telling hibernate this class treat as entity and need to save it the database.
and @ID means it telling hibernate this property treat as primary key of the table.
these are two minimum required annotation we have use for saving the object in the database.

Now we move to next step create service method to save the model object in the database.
Using the Hibernate API
  • Create a session factory
  • create a session from the session factory
  • Use the session to save model objects
Step 3: HibernateTestDemo.java
package com.sdnext.hibernate.tutorial;

import java.util.Date;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

import com.sdnext.hibernate.tutorial.dto.UserDetails;
public class HibernateTestDemo {
    public static void main(String[] args)
    {
       //Create the model object
       UserDetails user = new UserDetails();
        user.setUserId(1);
        user.setUserName(“Dinesh Rajput”);
   
       // Create Session Factory Object using Annotation Configuration
        SessionFactory sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory(); 
   
      //Create Session object from session factory object
        Session session = sessionFactory.openSession();
        session.beginTransaction();
   
       //Use the session to save model objects
        session.save(user);
        session.getTransaction().commit();
        session.close();
       }
}

Now run application now we get a Table with name UserDetails as its model class name with two columns name are ID and UserName as class property name.

Next Chapter we will write hibernate application using mapping file for the model class

                    <<Previous Chapter 3<<    >>Next Chapter5>>




View Comments