Monday, August 26, 2013

Hibernate Day3.. Simple Hibernate Example With Annotations


I am going to explain with simple... Friend class.


@Entity
public class Friend {
    @Id @GeneratedValue
    private int fid;
    private String fname;
    private String lname;


1)First thing you have to do is mark your class with @Entity
2)The class name will be taken as default table name in to which Friend object is going
   to be stored.We can override the default with other annotations.We will see it later.
   Property names becomes the column names in the table.We can override default
   and specify the new columnname in to which we need hibernate to store the values.
3)You have to annotate the property which acts as your primary key with @Id annotation. In the above
   example I have marked fid as my primary key.
4)@GeneratedValue means while saving friend we don't provide fid in to the object,
   hibernate helps us in generating a unique primary and sets in to the table.

5)Here is the new hibernate.cfg.xml.Only change you observe is the mapping element.
Instead of specifying the hbm files, we have to specify the classes which are
annotated.

<?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>
    <property name="hibernate.show_sql">true</property>
    <mapping class="annotationspkg.Friend"/>
   
  </session-factory>
</hibernate-configuration>

6)Instead of Configuration object, you need to use AnnotationConfiguration object.
   AnnotationConfiguration has the ability to read the classes annotated with the
  annotations.

7)Run the main method in Friend.java to test the annotations example

Imp Note:

In the example I uploaded I used AnnotationConfiguration but from hibernate3.6,we
can use.. Configuration itself as it has been enhanced to understand... annotations.

AnnotationConfiguration is deprecated from 3.6 release....


 Uploaded the example in the following URL

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











Sunday, August 25, 2013

Hibernate Day2 on Mapping Java objects having one to many relationship

How to store Continents having set of country objects ?
-------------------------------------------------------------------------

I am going to take example of Continents and Countries to explain example on One-to Many relationship.

As every one knows every Continent can have more than one countries.

Steps to store Continents and its Countries
---------------------------------------------------------

1)First create ContinentTo.Create continId and contiName.These properties are not new.
   The new property we need is a countries property which is Set.When you are working
   with hibernate.. you have to choose interface type(Set) in the left side as in the following
   declaration.There is the reason to do that.. we will see in next posts to keep the example
   simple.

   private Set countries = new HashSet();

  The countries set is going to hold countries for a Continent.

2)Create getter and setters for above 3 properties.

3)Create the following continents.hbm.xml file

   <?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.ContinentTo" table="dbcontinents">
    <id name="contiId" column="dbcontiId">
      <generator class="increment"/>
    </id>
    <property name="contiName" column="dbContiName"/>
    <set name="countries" inverse="true">
      <key column="contiFk" ></key>
      <one-to-many class="javalearners.CountryTo"/>
    </set>
</class>
</hibernate-mapping>

There is nothing new in the above hbm except set element.

4)We will discuss the <set element in the above hbm file which is used to map countries in to a
   seperate table.

5) <set name="countries" inverse="true">
      <key column="contiFk" ></key>
      <one-to-many class="javalearners.CountryTo"/>
    </set>

6)In the above element name attribute value matches the set variable declared in our ContinentTo.java

7)For one to many relationship in the database the most important thing is the foreign key right ?
   It is the foreign key in the countries table that links continents and countries tables together.

8)So, we need to specify the foreign key column using <key element. Specify the foreign key
column which is going to hold.. the foriegn key.In my example I have given column contiFk..
that means if I store Continent Asia with 2 countries India and China.

9)In database. if Contient Asia is stored with primary key 1 in continents table,then in countries
   table 2 countries will be stored and in each record 1 is stored in contiFk column in countries
   table. That means we can understand that these countries belong to Continent 1 which is
  Asia.

10)We have to specify the class to which Continent is having one to many relationship using
     <one-to-many element>.Just specify the class in class atrribute's value.

11)Create countriesTo and Countries.hbm.xml.Here is countries.hbm.xml.
     There is nothing new in this xml.

<?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.CountryTo" table="dbcountries">
    <id name="countryId" column="dbcountryid">
      <generator class="increment"/>
    </id>
    <property name="countryName" column="dbcountryname"/>
   
</class>
</hibernate-mapping>

12)Declare both mapping files in 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" >create</property>
    <property name="hibernate.show_sql">true</property>
    <mapping resource="student.hbm.xml"/>
    <mapping resource="continents.hbm.xml"/>
    <mapping resource="countries.hbm.xml"/>
  </session-factory>
</hibernate-configuration>


13)I have added new property called hibernate.show_sql and set it to true.
     What it does is,hibernate will show the sql that it is generating to the console.

    Following are the lines that got printed on my netbeans console after I set to
    true.This is very useful to find out where we are doing wrong.

  INFO: schema export complete
Hibernate: select max(dbcontiId) from dbcontinents
Hibernate: select max(dbcountryid) from dbcountries
Hibernate: insert into dbcontinents (dbContiName, dbcontiId) values (?, ?)
Hibernate: insert into dbcountries (dbcountryname, dbcountryid) values (?, ?)
Hibernate: insert into dbcountries (dbcountryname, dbcountryid) values (?, ?)
Hibernate: update dbcountries set contiFk=? where dbcountryid=?
Hibernate: update dbcountries set contiFk=? where dbcountryid=?

14)Uploaded the complete example to the following URL.

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

Hope you understand how to map.. objects with one to many relationship..

View of the Continents and Countries tables that got created by hibernate
 automatically.You can see the CONTIFK in the countries table.1 means
 it belong to Continent ASIA.


















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..