Wednesday, 24 December 2014

First Hibernate Application


Download jars required to run your application and place them in application class path. You can download jar files for hibernate from location http://hibernate.org/orm/downloads/.

Step1 : Create configuration file “hibernate.cfg.xml” and place it in application class path.

Hibernate.cfg.xml
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/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/sample</property>
    <property name="connection.username">root</property>
    <property name="connection.password">tiger</property>
    
    <!-- Enable the logging of all the generated SQL statements to the console -->
    <property name="show_sql">true</property>
    
    <!-- Format the generated SQL statement to make it more readable, -->
    <property name="format_sql">false</property>
    
    <!-- Hibernate will put comments inside all generated SQL statements to hint what’s the generated SQL trying to do -->
    <property name="use_sql_comments">false</property>
    
    <!-- This property makes Hibernate generate the appropriate SQL for the chosen database. -->
    <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
    
    <!-- Drop and re-create the database schema on startup -->
    <property name="hbm2ddl.auto">create</property>
    
    <!-- mappings for annotated classes -->
    <mapping class="myFirstHibernate.Employee" />
    
  </session-factory>
  
</hibernate-configuration>


Go through the comments in “hibernate.cfg.xml”, these are self-explanatory.

Step 2: Create model class
package myFirstHibernate;

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

@Entity
public class Employee {
  @Id
  private int id;
  private String firstName;
  private String lastName;
  private String designation;
  private int age;
  private double salary;
  
  public Employee(int id, String firstName, String lastName,
      String designation, int age, double salary) {
    super();
    this.id = id;
    this.firstName = firstName;
    this.lastName = lastName;
    this.designation = designation;
    this.age = age;
    this.salary = salary;
  }
  
  public int getId() {
    return id;
  }
  
  public void setId(int id) {
    this.id = id;
  }
  
  public String getFirstName() {
    return firstName;
  }
  
  public void setFirstName(String firstName) {
    this.firstName = firstName;
  }
  
  public String getLastName() {
    return lastName;
  }
  
  public void setLastName(String lastName) {
    this.lastName = lastName;
  }
  
  public String getDesignation() {
    return designation;
  }
  
  public void setDesignation(String designation) {
    this.designation = designation;
  }
  
  public int getAge() {
    return age;
  }
  
  public void setAge(int age) {
    this.age = age;
  }
  
  public double getSalary() {
    return salary;
  }
  
  public void setSalary(double salary) {
    this.salary = salary;
  }
  
}

@Entity annotation specifies that this class is an entity and to be persisted in database.

@Id annotation specifies primary key of this entity.

Step 3: Our model class and configurations are ready. Below are the steps to persist our model object to database.
       a. Create SessionFactory object
       /* Step 1: Create session factory */
  private static SessionFactory getSessionFactory() {
    Configuration configuration = new Configuration().configure();
    StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().
    applySettings(configuration.getProperties());
    SessionFactory factory = configuration.buildSessionFactory(builder.build());
        return factory;
    }

b. Get session from session factory.
       Session session = sessionFactory.openSession();
c. Begin transaction, save objects and commit transaction. finally close session
session.beginTransaction();
session.save(emp1);
session.save(emp2);
session.save(emp3);
session.save(emp4);
session.getTransaction().commit(); 
session.close(); 


Step 4: Run above class, you will get output like below.
package myFirstHibernate;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;


public class TestEmployee {
  
  /* Step 1: Create session factory */
  private static SessionFactory getSessionFactory() {
    Configuration configuration = new Configuration().configure();
    StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().
    applySettings(configuration.getProperties());
    SessionFactory factory = configuration.buildSessionFactory(builder.build());
        return factory;
    }
  
  public static void main(String args[]){
    Employee emp1 = new Employee(1, "Hari Krishna", "Gurram", "Senior Software Developer", 26, 80000);
    Employee emp2 = new Employee(2, "Shreyas", "Desai", "Team Manager", 35, 150000);
    Employee emp3 = new Employee(3, "Piyush", "Rai", "Senior Software Developer", 26, 100000);
    Employee emp4 = new Employee(4, "Maruti", "Borker", "Software Developer", 26, 60000);
    
    SessionFactory sessionFactory = getSessionFactory();
    Session session = sessionFactory.openSession();
    session.beginTransaction();
    session.save(emp1);
    session.save(emp2);
    session.save(emp3);
    session.save(emp4);
    session.getTransaction().commit();
    session.close();   
  }
}
 

Step 4: Run above class, you will get output like below.
Hibernate: drop table if exists Employee
Hibernate: create table Employee (id integer not null, age integer not null, designation varchar(255), firstName varchar(255), lastName varchar(255), salary double precision not null, primary key (id))
Dec 19, 2014 9:38:51 PM org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: HHH000230: Schema export complete
Hibernate: insert into Employee (age, designation, firstName, lastName, salary, id) values (?, ?, ?, ?, ?, ?)
Hibernate: insert into Employee (age, designation, firstName, lastName, salary, id) values (?, ?, ?, ?, ?, ?)
Hibernate: insert into Employee (age, designation, firstName, lastName, salary, id) values (?, ?, ?, ?, ?, ?)
Hibernate: insert into Employee (age, designation, firstName, lastName, salary, id) values (?, ?, ?, ?, ?, ?)


You can observe output, by default, hibernate uses class name as table name and instance field names as column names. We will see in subsequent posts how to change this behavior.

Step 5: You can check by opening sql prompt.

mysql> select * from employee;
+----+-----+---------------------------+--------------+----------+--------+
| id | age | designation               | firstName    | lastName | salary |
+----+-----+---------------------------+--------------+----------+--------+
|  1 |  26 | Senior Software Developer | Hari Krishna | Gurram   |  80000 |
|  2 |  35 | Team Manager              | Shreyas      | Desai    | 150000 |
|  3 |  26 | Senior Software Developer | Piyush       | Rai      | 100000 |
|  4 |  26 | Software Developer        | Maruti       | Borker   |  60000 |
+----+-----+---------------------------+--------------+----------+--------+
4 rows in set (0.00 sec)


That’s it we are done with our first hibernate application. It is time to make hands dirty with hibernate.
Prevoius                                                 Next                                                 Home

No comments:

Post a Comment