Friday, June 28, 2013

Hibernate Simple Example


Here we will configure hibernate in eclipse and write our first hibernate program to persist Student data in to a DATABASE.


Before stating this program, there are some prerequisites which you need to have on your system. Please find the below.

  • Database (Oracle).
  • Eclipse (IDE).
  • JDK 1.5 or above.
  • Hibernate Jars


Make Sure Finally your Project Structure should be like below.






Start Program :


Open Eclipse and go to the File and select Java Project from the list. See below.

































Provide the Project Name and click Finish.

Right click on the project and select New --> Folder and give name as jars.

Add the Downloaded jar files in jars folder under the project like in the first screen above.


Add these jars in to a class path like below.




















Right click on the project and select New  --> Package and provide package name.

and right click on the package and select New --> Class.









Create a class with the name Student.java and provide the following code in this file.

Before you make sure you have table with some columns in your Database, or else you can create a table by following the below query.


CREATE TABLE STUDENT(
    ID            NUMBER(16)          NOT NULL,
    NAME          VARCHAR2(256),
    ADDRESS       VARCHAR2(16)
)


Student.java:

package org.nagendra.learning;

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

@Entity(name = "STUDENT")
public class Student
{
@Id
@Column(name = "ID", nullable = true)
private Integer id;

@Column(name = "NAME")
private String name;

@Column(name = "ADDRESS")
private String address;

public Student()
{
}

public Integer getId()
{
return id;
}

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

public String getName()
{
return name;
}

public void setName( String name )
{
this.name = name;
}

public String getAddress()
{
return address;
}

public void setAddress( String address )
{
this.address = address;
}

}



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">oracle.jdbc.driver.OracleDriver</property>  
        <property name="connection.url">jdbc:oracle:thin:@IP:Port/databasename</property>  
        <property name="connection.username">username</property> 
        <property name="connection.password">password</property> 
  
        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">1</property>  
  
        <!-- SQL dialect -->  
        <property name="dialect">org.hibernate.dialect.OracleDialect</property>  
  
        <!-- Echo 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="org.nagendra.learning.Student"></mapping>  
  
    </session-factory>  
  
</hibernate-configuration>


In details of each and every property:


<property name="connection.driver_class">: 
Need to specify  JDBC driver class.

<property name="hibernate.connection.url "> :

specify JDBC URL to the database instance.

<property name="hibernate.connection.username " >:

Specify database username

<property name="hibernate.connection.password" >:

Specify database password

<property name="hibernate.connection.dialect" >:

This property makes Hibernate generate the appropriate SQL for the chosen database.

<property name="hibernate.connection.pool_size " >:

This property limits the number of connections waiting in the Hibernate database connection pool.

<property name="show_sql" >:

If you specify this property to be true then all sql statement will be printed to console.

<property name="hbm2ddl.auto" >:

It specify operation on your database schema.Whether to drop and recreate your database schema or update current schema.

<mapping class="org.arpit.javapostsforlearning.User" >:

Here you need to specify all java classes for which you want to create a table in database.You need to specify all entity classes here.


Add the  hibernate.cfg.xml file in to the project properties source folder like below. To go the Properties popup, select project and select properties in the below.


























HibernateMain.java :



package org.nagendra.learning;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

public class HibernateMain
{
public static void main( String[] args )
{
Configuration configuration = new Configuration();
configuration.configure();

ServiceRegistry sr = new ServiceRegistryBuilder().applySettings(configuration.getProperties())
                .buildServiceRegistry();

SessionFactory sf = configuration.buildSessionFactory(sr);

Student student = new Student();
student.setId(1);
student.setName("Nagendra");
student.setAddress("Bangalore");

Session ss = sf.openSession();
ss.beginTransaction();
ss.save(student);
ss.getTransaction().commit();
ss.close();
}
}



Now your project is ready.

Just right click on the HibernateMain.java and run as java application.

No comments:

Post a Comment