Tuesday, 6 October 2015

Life Cycle

Life Cycle


Actually POJO class object has following three states like-
Transient state
Persistent state
Detached state

1
Pojo obj=new Pojo();             //transient object
2
obj.setName("CST"); 
3
Session sec=fact.openSession();  //Session internally calls persistentContext method
4
                               //Session sec=new persistentContext();
5
sec.save(obj);
6
​



To Insert:
Session sec=fact.openSession();
sec.save(obj);

To Fetch:
Object o=sec.load(Pojo class.newInteger(101);
Pojo obj=(Pojo)o;
obj.getName(); 

To Delete:
Object o=sec.load(Pojo class.newInteger(101);
Pojo obj=(Pojo)o;
sec.delete(obj); 

To Update:
Object o=sec.load(Pojo class.newInteger(101);
Pojo obj=(Pojo)o;
obj.setId(104); obj.setName("abc"); tx.commit(); 

Transient & Persistent states:
> Whenever an object of a pojo class is created then it will be in the Transient state.
> When the object is in a Transient state it doesn't represent any row of the database, i.e. it is not associated with any Session object.
> If we modify the data of a pojo class object, when it is in transient state then it doesn't effect on the database table.
> When the object is in persistent state, then it represents one row of the database, if the object is in persistent state then it is associated with the unique Session.
> If we want to move an object from persistent to detached state, we need to do either closing that session or need to clear the cache of the session.
> If we want to move an object from persistent state into transient state then we need to delete that object permanently from the database.
1
public class ClientProgram
2
{ 
3
  public static void main(String[] args)
4
  {
5
      Configuration cfg = new Configuration();
6
      cfg.configure("hibernate.cfg.xml"); 
7
      
8
        SessionFactory factory = cfg.buildSessionFactory();
9
      Session session = factory.openSession();
10
   
11
      // Transient state_____start
12
      Product p=new Product();
13
      p.setProductId(101);
14
      p.setProName("iPhone");
15
      p.setPrice(25000);
16
      // Transient state_____end
17
   
18
      // Persistent state_____start
19
      Transaction tx = session.beginTransaction();
20
      session.save(p);
21
      System.out.println("Object saved successfully.....!!");
22
      tx.commit();
23
      // Persistent state_____end  
24
   
25
      session.close();
26
      factory.close();
27
      }

1. In the above client program, line numbers 16 to 19 we just loaded the object and called the corresponding setter methods, it is not related to the database row.
2. If you see, line number 24 we called save method in the Session Interface, means the object is now having the relation with the database
3. If we want to convert the object from Transient state to Persistentstate we can do in 2 ways:
1. By saving that object like above
2. By loading object from database
If we do any modifications all the changes will first applied to the object in session cache only (e.g. If we do the modifications 5 times, then 5 times we need to save the changes into the database, which means number of round trips from our application to database will be increased. Actually, if we load an object from the database, first it will be saved in the cache-memory. So, if we do any number of changes all will be effected at cache level only and finally we can call save or update method with a single call such that the data will be saved into the database.
If we want to save an object into database then we need to call any one of the following three methods
(1) save()
(2) persist()
(3) saveOrUpdate()
If we want to load an object from database, then we need to call either load() or get() method(s).

Transient:
One newly created object,with out having any relation with the database, means never persistent, not associated with any Session object.

Persistent:
It has the relation with the database, associated with a unique Session object.
It is also called context stage. It is predefinely created.
It is an abstract class to hide some method.
All the objects which are available for connection with database must be created and loaded and should be made active before data is coming.
All the data should be sent in persistent state first and then in database.

Detached:
Previously having relation with the database [persistent], now not associated with any Session.

Stages:

Stage 1:
• Receives the value.
• Makes public data into private.
• Makes received data light weight.
• Makes received data encapsulated.

Stage 2:
Creates Persistent stage or context stage
• Driver
• Connection
• User Name
• Password
• Dilect

Stage 3:
Transient stage
• Sends data in persistent stage
• Makes tablespace in persistent stage. 

Monday, 5 October 2015

Hibernate File System

Hibernate File System


File System of hibernate deals with the flow of control from one file to another. There are various files that are created while using hibernate framework.

Flow of Control of Hibernate Files
1. First diagram explains the flow by taking an example. A Register.html file is made which contains the requirements of username and password. On clicking Submit button, the control goes to web.xml which is used to match the URL pattern. After that the flow goes to Servlet.java which contains the code for Hibernate explained in subsequent diagrams. Alongwith Servlet.java, another file named POJO.java is created which contains getters and setters and makes the object lightweight. The code of hibernate.cfg.xml contains the mapping resource- hibernate.hbm.xml, which is used to match the POJO objects and the database values.


2. This diagram explains the inner working of Servlet.java code. First of all, Configuration is a class that implements Serializable containing methods viz. readObject(),writeObject(), readObjectnoData(). The constructor Configuration() calls hibernate.properties jar which writes the objects created by hibernate.cfg.xml, which are dialect,URL,driver_class,username,password etc.


3. Given diagram explains that SessionFactory is an interface that implements Referenceable and Serializable and contains its respective methods.Now, buildSessionFactory method is used to execute the pre-defined values contained in hibernate.cfg.xml.


We have already learnt that hibernate is an open source object/relational mapping tool for Java. It lets us develop persistent classes. The goal of Hibernate is to relieve the programmer from 95 percent of common data persistence related programming tasks. 
Following diagram tells the files which are supposed to be created or/and is created by hibernate itself:



1. First, whenever Hibernate is created, a POJO class or the constructor oriented class is created which in the above diagram is  DetailPojo.java. 
2. Next, in hibernate.cfg.xml i.e. in hibernate configuration xml, mapping resource is added and is mapped to a mapping file.
3. After that, in hibernate.hbm.xml, which is the mapping file, object's name, classes, subclasses, properties and discriminator are added.
4. Finally, a servlet is made which is SignUp.java in the above example which includes SessionFactory, Transaction etc.
That is how the basic files in hibernate is created.

Downloading Hibernate
1. Considering you have latest Java version installed on your system, if you want to use Hibernate with Netbeans IDE then that can be done while installing Netbeans IDE.
2. If any other editor is to be used then, download Hibernate tools and Distributions from http://www.hibernate.org/downloads.
3. Zip files are downloaded that can later be unzipped and used as shown below.



Hibernate Prerequisites
Following are the basic list of packages/libraries that must be unstalled before using Hibernate.



Terms associated with Hibernate

1. HQL - HQL is abbreviation of Hibernate Query Language. It is SQL inspired language provided by hibernate. Developer 
              can write SQL like queries to work with data objects.

2. Dialect - Each SQL vendor has its own set of syntax. This is known as dialect. In order to generate appropriate SQL query Hibernate needs to know, for which DataBase, query is to be generated. Hibernate does it by org.hibernate.dialect.Dialect class and its subclass for each vendor.
   Example:
                  DB2 : org.hibernate.dialect.DB2Dialect
                  MySQL : org.hibernate.dialect.MySQLDialect

3. Hibernate Association - Any Table in DataBase could be connected to other tables in same or other Database. And 
                                         these tables could be associated with each other via some keys (primary or foreign). This kind
                                         of scenario can be handled with association.
Example: There are two tables in a Database, Student & Subject. A student can study one subject or more subjects. So, every student will have only one entry in Student table but Subject table could contain more than one values for corresponding record in Student table. Association mapping are used to map a Java Object to DataBase table's columns.

i. Entities involved in mapping:-
a)  Class (Persistence) (POJO)
b)  Database Table
c)  Mapping file (.hbm)

ii. Types of Association:-
a) Unidirectional Association:
    Many To One
    One to One
    One to Many
b) Unidirectional Association with join Table
    Many To One
    One to One
    One to Many
    Many to Many
c) Bidirectional Association
    One to Many / Many to One
    One to One
d) Bidirectional Association with join Table
    One to Many / Many to One
    One to One
    Many to Many

Friday, 2 October 2015

Hibernate Architecture

Topics

1. Introduction to Hibernate Architecture

There are 4 basic layers in hibernate architecture i.e.1. Java application layer
2. Backend layer
3. Hibernate framework layer
4. Database layer




The Hibernate framework contains following levels:

Java Application:
The java application uses the hibernate framework .

Persitent Class Object:
Hibernate provides transparent persistence for Plain Old Java Objects (POJOs). The only strict requirement for a persistent class is a no-argument constructor.

SessionFactory:
SessionFactory is actualy an interface that extends Referenceable and Serializable.
The org.hibernate.SessionFactory interface provides factory method to get the object of Session.
An application usually has a single SessionFactory. 
The Configuration class can be used to create SessionFactory object which serves as a factory class that creates Session objects.
It holds second level cache of data.

Session:
The org.hibernate.Session interface provides methods to insert, update and delete the object. 
A Session is used to get a physical connection with a database.
The Session object is lightweight and designed to be instantiated each time an interaction is needed with the database. Persistent objects are saved and retrieved through a the Session object.
It is factory of Transaction, Query and Criteria. It holds a first-level cache (mandatory) of data. 

Transaction:
The org.hibernate.Transaction interface provides methods for transaction management.
A transaction represents a unit of work. If you want the database to do some work for you, then we need to start a transaction. 

ConnectionProvider:
It is a factory of JDBC connections ie provide the connection between jdbc and database. It abstracts the application from DriverManager or DataSource. 

Thursday, 1 October 2015

Hibernate

Topics

1. Introduction to hibernate.


Hibernate is a pure Java object-relational mapping (ORM) and persistence framework that allows you to map plain old Java objects to relational database tables using (XML) configuration files. Its purpose is to relieve the developer from a significant amount of relational data persistence-related programming tasks. Hibernate simplifies:
1. Saving and retrieving your domain objects
2. Making database column and table name changes
3. Centralizing pre save and post retrieve logic
4. Complex joins for retrieving related items
5. Schema creation from object model.
So, Hibernate is simple ORM (Object Relational Mapping) tools that provides a framework for mapping an object-oriented domain model to a relational database. 



2. What is  ORM.

Actually ORM is complete MVC (Model View and Control) based application.
the four ORM levels are in hibernate?
Following are the four ORM levels in hibernate:
1. Pure Relational
2. Light Object Mapping
3. Medium Object Mapping
4. Full Object Mapping



3.  Advantages of Hibernate:
I. Auto DDL (Data Definition Language) Command: DDL query means Create Table, Alter Table, Rename Table. Hibernate automatically create table.
II. Support database independent query: Hibernate support database independent query language i.e. HQL (Hibernate Query Language). 
III. Cache Support: cache actually stores the data already loaded from the database.
IV. Generator Support: Provide the facility to create primary key, foreign key, sequence generator.
V. Data Validation Support: Hibernate validation is recommended validation. Hibernate filter the data if data is valid then it send to database.
VI. Hibernate code is Exception free.
VII. ORM Relationalship support: Is like IS-A, HAS-A Relation .