Thursday, August 22, 2013

Hibernate Day1 on What is Hibenate and how to store Student Object in the database using Hibernate

What is Hibernate ?
-------------------------

Hibernate is an ORM framework.

What it does ?
-------------------

If you give the Java object,hibernate generates SQL statements(Insert/Update/delete) in background.
Very good job by Hibernate right ?

How will hibernate know to which table it needs to store the properties in Java Object ?
---------------------------------------------------------------------------------------------------------------
2 Types of XML files that we are going to write helps hibernate in identifying database related
details and Table&Column Information.

1)hibernate.cfg.xml

In this xml we have to specify the DriverClass name,URL of the database to
which we are going to connect,username,password and many more........If you observe the
following configuration file.. you will realize that these are the properties we use to specify
while connecting to database from JDBC programme.But.. in hibernate we specify in XML
format.

Let us see the contents of 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.OracleDialect</property>
    <property name="hibernate.connection.driver_class">oracle.jdbc.OracleDriver</property>
    <property name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:XE</property>
    <property name="hibernate.connection.username">hr</property>
    <property name="hibernate.connection.password">hr</property>
    <property name="hibernate.hbm2ddl.auto" >update</property>
    <mapping resource="student.hbm.xml"/>

  </session-factory>
</hibernate-configuration>

2)Mapping Files or Hbm files?

Mapping files contain the information on the table name and columns to which the properties in
java object need to be stored.

Suppose if there is Student class with following properties
a)sid
b)sname

In Mapping file we have to specify to which table in the database.. we need to store student
object. We need to specify the columns in the table to which sid and sname to be stored.

How many mapping files we need to write ?

It is good to write.. one mapping file for every Java Class.But we can map multiple java classes
in one hbm file also.


Steps to store Student java objects in to Students table:

1)First create hibernate.cfg.xml file with following contents.You have to specify db url,
   username and password which will be used by hibernate to create connection to db
   when required.This file is the way we specify hibernate about our database details.

<?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.OracleDialect</property>
    <property name="hibernate.connection.driver_class">oracle.jdbc.OracleDriver</property>
    <property name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:XE</property>
    <property name="hibernate.connection.username">hr</property>
    <property name="hibernate.connection.password">hr</property>
    <property name="hibernate.hbm2ddl.auto" >update</property>
    <mapping resource="student.hbm.xml"/>
   
   
  </session-factory>
</hibernate-configuration>

2)Create student.hbm.xml,this file contains table name and columns to which student
   records are going to be stored.

 <?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="javalearners.Student" table="STUDENTS">
    <id name="sid" column="sid">
      <generator class="increment"/>
    </id>
    <property name="fname" column="dbfname"/>
    <property name="lname" column="dblname"/>
</class>
</hibernate-mapping>

Let us see important things in student.hbm file:

a)We have to specify our Student class with package name as name attribute's value.
    We have to specify the table name to which student records get stored as table
     attribute's value.

b)We have to specify which property in our class is primary key.We specify it by
    using id element.

c)What is generator element ?

    Whenever we save student object hibernate will generate student id and store it in
    sid column of students table.If we want to pass the sid then generator should be
    "assigned" instead of "increment".

    There are many types of generators.In above example.. we used increment generator.
    We will see other generators in next posts.

d)Finally for every property in student class we need to specify the column in to which
   the property value is going to be stored.

   In the above example we are sepcifying fname and lname in student object are going to
   be stored in dbfname and dblname columns respectively.


3)After creating student.hbm.xml, you have to specify this file in hibrnate.cfg.xml.Every
   hbm file need to be specified in hibernate.cfg.xml.Refer the mapping element in
   configuration file(hibernate.cfg.xml).

   <mapping resource="student.hbm.xml"/>


Next step is create a java class to test our example.

4)We have to create Configuration object and call configure method.
    configure method in configuration class tries to find out the file with name "hibernate.cfg.xml"
    in our classpath and loads it.Don't forget to call configure method.

Configuration conf = new Configuration().configure();

5)Next we have to create SessionFactory Object by saying..
   SessionFactory sf = conf.buildSessionFactory();

  SessionFactory is like the factory to get session(connection) objects.

6)Get the session object from SessionFactory object.
   Session ses = sf.openSession();

   You can think session object like connection object in JDBC.Session object is
    like a wrapper which contains connection object.

7)Create Student object with fname and lname and call save method.
   You have to enclose save in the transaction and call t.commit otherwise changes
   won't get reflected in database.

      Transaction t = ses.beginTransaction();
           ses.save(st);
        t.commit();
  
8)When you pass the student object to save method.. hibernate automatically generates
    SQL statements and inserts student record in to Database.

Here is the result..





How to create Hibernate project in Netbeans ?


1)Go to File->NewProject->Java->JavaApplication->Provide Your project name->
Finish

2)RightClick project->properties->Choose Libraries->AddLibrary->
   select Hibernate JPA->Click on AddLibrary button.





Uploaded the Code in the following URL.

https://docs.google.com/file/d/0BwZaaDwCofcNTk9BUXoydk1iQVU/edit?usp=sharing


Very easy to save the records in to database right...........,Only thing is we have to provide
long xml files :)

Hope you understand the HelloWorld example in hibernate....Post your comments or doubts..in
comments section and I will try to clear asap.. when I get time..




5 comments:

  1. is id tag in hbm.xml is compulsory?

    ReplyDelete
  2. Hi Mukteswari
    Id is very important...

    id denotes the primary key..property
    In my example I have denoted that sid
    is my primary key by specifying it as
    id element

    ReplyDelete
  3. This comment has been removed by the author.

    ReplyDelete
  4. Thanx Anil.. which means the id tag is mandatory..

    ReplyDelete
  5. Mukteswari
    You can join my java group...
    https://www.facebook.com/groups/148741851992250/

    ReplyDelete