Monday 7 October 2013

Introduction to Hibernate and ORM

Hibernate 1
  • Hibernate by defination it is an ORM(Object Relational Mapping) tool

  • ORM means which is used to map plain java objects to a tables Relational Database and vice versa



Lets we see in details of hibernate:
  • you have a java application which connects a relational database for example MySql
  • And I have a student class which contains members(variables) like name, Rollno, Address, Mobile which represents students information
  • Now you have created a Student object: like below
Student student=new Student(“Raj series”, 1, “India Hyderabad”, “98xxxxxx38”);
  • Now these information should store in the database which is there student object in to the student_info table.


  • If you are not using ORM framework like hibernate, you do this task using jdbc, and typically your code will look like this below:
public void insertStudentinfc(Student student)
{
Connection conn=null;
Statement stmt=null;
try
{
//step 1: Register JDBC DRIVER
class.forName(“con.mysqljdbc_Driver”);
//STEP 2: OPEN A CONNECTION
System.out.println(“connecting to a selecting database”);
conn.DriverManager.getConnection(“jdbc:mysql://localhost/STUDENTS”,”username”, “password”);
System.out.println(“connected database successfully”);

//step 3 write code to map java object student to the STUDENT_INFO table
System.out.println(“inserting records into the table”);
stmt=conn.createStatement();
String sql=”INSERT INTO STUDENT_INFO(Name,Roll_No,Address, Mobile)”+”VALUES(student.getName(),student.getRoll_No(),student.getAddress(),student.getMobile())”;
stmt.executeUpdate(sq)
System.out.println(“inserted student information into the STUDENT_INFO”);
}
catch(SQLException se)
{
//handling the jdbc errors
se.printStackTrace();
}
catch(Exception e)
{
//hadling errors for Class.forName()
e.printstackTrace();
}
finally
{
//STEP 4: finally block used to close resources
try
{
if(stmt!=null)
conn.close();
}
catch(SQLException se)
{
//do nothing
}
try
{
if(conn!=null)
conn.close();
}
catch(SQLException se)
{
se.printStackTrace();
}//end finally try
}
}
}
// if you are using Hibernate, simple one statement is enough


Student student=new Student(“Raj series”, 1, “India Hyderabad”, “98xxxxxx38”);



  • We observe passing student object to the function insertStudentInfo() and manually mapping to the member variable to the columns of the table using sql query and here lies the major problem hibernate says as a java programmer : Why are you writing the SQL Queries in the java code(application)? Just leave that job to me, just pass the java object which you want to store or persist and implicitly I will generate and optimize SQL Query, and store the data into the data base table. So if you are using hibernate, the same code would like this:

public void insertStudentInfo(Student student)
{
Session session=Factory.openSession();
Transaction tx=null;
try{
tx=session.beginTransaction();
session.save(student);
tx.commit();
}
catch(HibernateException e)
{
if(tx!=null) tx.rollback())
e.printStackTrace();
}
finally
{
session.close();
}
}


  • just observe the above java code, there is no sql queries in your java application
  • Reduced the 80% of code compared to jdbc. It means that better code readability
  • Just pass the object to the save method and insert the record into the record
  • similarly if you want to retrieval the records in jdbc from the StudentInfo table in java application you first get the ResultSet and you frame a java object basically a collection object for example a list (ie: studentInfoList.add(student);)
Data Retrieval using JDBC:


ResultSet rs=stmt.executeQuery(“SELECT Name,Roll_No,Address,Mobile FROM Student_Info”);




//fetch each row from the result set
//and create a list object containing Student Info


List studentInfoList=new LinkedList();
while(rs.next())
{
String name=res.getString(“Name”);
String rollNo=res.getInt(“Roll_No”);
String address=res.getString(“Address”);
String mobile=res.getInt(“Mobile”);

//inserting records into the student object
Student student =new Student(name, rollNo, address, mobile);
studentInfoList.add(student);
}


  • For example a list (studentInfoList.add(student))result set , hibernate says
  • time: 2:38


hibernate syllabus


    Introduction to ORM and Hibernate http://raj-hibernate.blogspot.in/2013/10/introduction-to-hibernate-and-orm.html
    Drawbacks of JDBC
    Advantages of HIBERNATE
    Hibernate Architecture
    Hibernate Configuration
    How to add Plugins- Features into Eclipse
   Steps to configure Hibernate in Java Application
creation of Hibernate  Project
first hibernate application
    Introduction to Session and SessionFactory
    Persisting Objects using Hibernate
    Inheritance Mapping
    Bidirectional Association Mapping
    Hibernate Query Language
    Caching Introduction
    Implementing Second Level Caching using EHCACHE
    Integrating Spring & Hibernate
    Integrating Struts & Hibernate
    Integrating JPA & Hibernate

Saturday 27 July 2013

first hibernate application



























steps:

1. create the java project:

go to file -> new->project->"give any name" i.e: HibernateAppli. click on next->finish button

2. Add jar files for hibernate
//download the hibernatjar files

to add the jar files: right click on your project->build path->Add external archives.

now select all the jar files as show in the image given below then click open.
3. in this example we are connecting the application with MySql database. So you must add the
(i have already installed MYsql database)
//download mysql jar files

go to project->right click->properties->click on java build path->click on Libraries->Add External JARs
click on ok

//creating first hibernate program

//creating package
 1. go to file->new->package->

Using the New Java Package wizard

Once the Java Package wizard comes up:

    Enter/confirm the source folder name

    Enter the package name

    Click on the Finish button


4. create the persistance class
create employee class into com.infy

now create a package as com.infy and create Employee class into com.infy package
->place the curson on newly created package(i.e infy.com)
->right click->choose class
new java class wizard shows
->give a class name. i.e Employee
->click on finish
5. create the mapping file for persistent class

->here we are creating the same mapping file, Right click on src->new->file->specify the file name(e.g:employee.hbm.xml)->ok
->it must be outside the package:

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
 <class name="com.infy.Employee" table="InfyEmployee">
 <id name="empNo">
 <generator class="assigned"></generator>
 </id>

 <property name="empName" length="20"></property>
 <property name="doj" type="Date" length="20"> </property>
 <property name="dob" type="Date" length="20"> </property>
 <property name="phno" type="String" length="12"></property>

 </class>
 </property-mapping>

->here persistance entity class is "Employee"

table is Database is "InfyEmployee"
here id property is empNo, here identifier generator


(5) create the Configuration file

configuration file contains all the informations for the database such as connection_url, driver_class, username,password etc
The hbm2ddl.auto property is used to create to create the table in the database automatically.
we will have in-depth learning about Dialect class in next topics. To create the configuration file, right click on src->new->file.
 specify the configuration file name e.g. hibernate.cfg.xml.

//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-confuguration>
<session-factory>
<!-- Database connection settings -->


 <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
 <property name="connection.url">jdbc:mysql:://localhost:3306/poc</property>
 <property name="connection.username">user</property>
 <property name="connection.password"/>

 <!--JDBC connection pool (use the built-in)-->
 <property name="connection.pool_size">1</property>


 <!--SQL dialect-->
 <property name="dialect">org.hibernate.dialect.MySQLDialect</property>

 <!--Disable the second -level ache-->
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>

 <!--Echo all executed SQL TO stdout-->
 <property name="show_sql">true</property

 <!--drop the existing tables and create new one-->
 <property name="hbm2ddl.auto">create</property>

 <!--mention here all the model classes along with their package name-->
 <mapping class="infy.com.Employee"/>

<session-factory>
<hibernate-configuration>


(6) create the class that retrieves or stores the persistent object
es
->in this class, we are simply storing the employee object to the database.













































Friday 26 July 2013

creation of Hibernate Project

creation of Hibernate  Project

  


we can create hibernate project as in two ways.

1. By creating normal java project (java perspective)
2. By creating Dynamic web project (jee perspective)


First Hibernate application with all CRUD operations


  • Let us create a Dynamic web project with JEE perspective:
  • Scenario: I want to automate Employee details. Properties like empno,empname,dateofbirth,dataofjoin,phno,should be stored in Db table.
  • i want to perform the following CRUD operation on Employee table in database
  1. INSERT employee details
  2. Select
  3. modify
  4. delete
create Dynamic Web Project "InfyEmployee" as below

1. choose new from file menu
2. choose dynamic web project
3. give project name: ex: InfyEmployee
4. click on finish
5. add all required jar files to the project:

Employee bean:

Now create a package as com.infy and create Employee class into com.infy package as shown below:

pakage com.infy;
import java.util.Date;
public class Employee
{
  private int empno;
  private String empName;
  private Date dob;
 private Date doj;
 private String phno

//setters and getters methods

}

/* here empNo is Identifier. All persistenses classes should only have T no-argument constructor or default constructor. Should not contain Parameter constructor*/









Tuesday 23 July 2013

Steps to configure Hibernate in Java Application

Steps to configure Hibernate in Java Application

  1. create configuration class object by loading configuration.xml file. We can load configuration.xml file by using configure() in configuration class.
         Configuration cf=new Configuration().configure("hibernate.cfg.xml"); 
now cf is able to read hibernate .cfg.xml using DOM parser.
2. create SessionFactory object using cf.
 SessionFactory sf=cf.buildSessionFactory();
Now sf is a hibernate SessionFactory interface object which maintains all the properties of hibernate.xml file.
step 3: create session object
Session session=sf.openSession();
step 4: create Transaction object by session object.

Transaction tx=session.beginTransaction();
step 5: use sesssion object for different CRUD operations.
step 6: finally commit the transaction by calling tx.commit();

classes and Interfaces can imported from the following packages

org.hibernate.*;
import org.hibernate.cfg.*;

How to add Plugins- Features into Eclipse

    How to add Plugins- Features into Eclipse

//yet to be started

Sunday 21 July 2013

Hibernate Configuration

Hibernate Configuration

WE can configure hibernate by adding the .jar(s) files to our java application

  • Required files of Hibernate Application. (Hibernate requires two XML files)
  1. mapping file
  2. configuration file (Hibernate.cfg.xml)
What is Mapping?

Mapping is a mechnism for establishing synchronization between object and row of the table.
Mapping can be done using 2 ways:
  1. XML (Mapping XML file)
  2. Annotations 
  •  
usage of  XML files for mapping are more effective and easy when compared with Annotations.

Syntax: for mapping with XML file:
 

<? xml version="1.0">
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/hibernate Mapping DTD 3.0//EN"
       "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
 <class name="POJO class name " table="table name">
   < id name ="variable name" column=" primary key column name"
     type="java/hibernate type"> <generate class="increment"></generator>
   </id>
  <property name="variable2 name" column="column name  in database"
   type="java/hibernate type"/>
 <property name="variable2 name" column="column name in database" type="java/hibernate type"/>
</class>
</hibernate-mapping>
  • we will include Hibernate DTD for auto complesion of XML mapping elements and attributes in our editor or IDE.
  • The DTD file is included in hibernate-core.jar
<class > element: class element is a child of hibernate-mapping tag. All persistent entity classes need a mapping to a table in the SQL database.

<id> element: Each instance is a row in the table. We need unique identifier property to map as primary key in the table to identify each row uniquely. The id element is the declaration of the identifier property.

<generator>  element: The nested generator element specifies the identifier generation strategy. Hibernate supports different identifier generation strategy algorithm. These strategies depends on configured database dialect.

<property> element:  specifies properties in a class other than id property. The name attribute of the property element tells Hibernate which getter and setter methods to use

configuration file( hibernate.cfg.xml)

configuration file is loaded in to an hibernate application when we run the hibernate application. Configuration file should have 3 kinds of properties.
  1. connection properties
  2. Hibernate properties
  3. Mapping file properties
  • we may have one or more configuration files based on number of databases we are using for getting date into our application.
  • if we want to populate data from two databases like Oracle, MySql then we must create two configuration files. i.e: Number of configuration files in the hibernate application =Number of databases used in application.
<hibernate-configuration>
 <session-factory >
              <!--connection  Properties--->
         <property name="connection.driver class">Driver class name
         </property>
         <property name="connection.url">URL</property>
         <property name="connection.user">user</property>
        <property name="connection.password">password</property>

             <!--END of connection properties-->
             <!--Hibernate properties-->
             <property name="show_sql">true/false</property>
             <property name="dialet">Database dialet class</property>
            <property name="hbm2dd1.auto">create/update or whatever</property>

           <!--END of Hibernate Properties-->

           <!--mapping file names-->
          <mapping resource="hbm file1 name.xml"/>
         <mapping resource="hbm file2 name.xml"/>
         <!--END of Related to the mapping-->
     </session-factory>
</hibernate-configuration>