5
* Hibernate is Persistence Framework is used to implement Persistence Logic or Database Operations. * Hibernate is a pure Java Object-Relational Mapping (ORM) and persistence framework that allows us 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. Advantage of Hibernate : * Hibernate is database independent, our code will work for all the Oracle, MySQL etc. * for better performance Hibernate provides two level of Cache – First Level, Second Level. * Fast Development, no need to write SQL Query. * Hibernate supports to configure both the types of Primary Key - Simple Primary Key & Composite Primary Key * Simple Primary Key – increment, hilo, sequence, seqhilo, uuid, guid, identity, native, assigned, select. # using increment <id name=”sid” column=”sid” type=”int”> <generator class=”increment”/> </id> # using uuid <id name=”sid” column=”sid”> <generator class=”uuid”/> </id> # using sequence <id name=”sid” column=”sid”> <generator class=”sequence”> <param name=”sequence”>SID_SEQ</param> </generator> </id> # using hilo <id name=”cid” column=”cid” type=”int”> <generator class=”hilo”> <param name=”table”>hi_value</param> <param name=”column”>next_value</param> <param name=”max_10”>10</param> </generator> </id> # using seqhilo <id name=”sid” column=”sid” type=”long”> <generator class=”seqhilo”> <param name=”sequence”>SID_SEQ</param> <param name=”max_10”>100</param> </generator> </id> * Steps to write Custom Primary Key through Core : import org.hibernate.id.IdentifierGenerator; class SidGenerator implements IdentifierGenerator{ public Serializable generate(SessionImplementor si, Object obj)throws HibernateException{} } Usage(in hbm) : <id name=”sid” column=”sid” type=”string”> <generator class=”com.jlcindia.hibernate.SidGenerator”> </id> * Steps to write Custom Primary Key through Annotation : class SidGenerator{ public static String getNextSid(){} } Usage(in main) : Student stu=new Student(SidGenerator.getNextSid(),”Krishu”,”Patna”,8888888); * Using Hibernate SQL Dialects , we can switch any databases without code change. Hibernate will generate appropriate hql queries based on the dialect defined. * Collection types in Hibernate : Bag, Set, List, Array, Map. * Configure Hibernate SessionFactory for 2 Databases import org.hibernate.SessionFactory;

Hibernate Complete Overview

Embed Size (px)

DESCRIPTION

Hibernate Complete Overview

Citation preview

Page 1: Hibernate Complete Overview

* Hibernate is Persistence Framework is used to implement Persistence Logic or Database Operations.* Hibernate is a pure Java Object-Relational Mapping (ORM) and persistence framework that allows us 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.

Advantage of Hibernate :* Hibernate is database independent, our code will work for all the Oracle, MySQL etc.* for better performance Hibernate provides two level of Cache – First Level, Second Level.* Fast Development, no need to write SQL Query.

* Hibernate supports to configure both the types of Primary Key - Simple Primary Key & Composite Primary Key * Simple Primary Key – increment, hilo, sequence, seqhilo, uuid, guid, identity, native, assigned, select. # using increment

<id name=”sid” column=”sid” type=”int”> <generator class=”increment”/></id>

# using uuid<id name=”sid” column=”sid”> <generator class=”uuid”/></id>

# using sequence<id name=”sid” column=”sid”> <generator class=”sequence”>

<param name=”sequence”>SID_SEQ</param> </generator></id>

# using hilo<id name=”cid” column=”cid” type=”int”> <generator class=”hilo”>

<param name=”table”>hi_value</param><param name=”column”>next_value</param><param name=”max_10”>10</param>

</generator></id>

# using seqhilo<id name=”sid” column=”sid” type=”long”> <generator class=”seqhilo”>

<param name=”sequence”>SID_SEQ</param><param name=”max_10”>100</param>

</generator></id>

* Steps to write Custom Primary Key through Core :import org.hibernate.id.IdentifierGenerator;class SidGenerator implements IdentifierGenerator{ public Serializable generate(SessionImplementor si, Object obj)throws HibernateException{} }

Usage(in hbm) : <id name=”sid” column=”sid” type=”string”><generator class=”com.jlcindia.hibernate.SidGenerator”>

</id>

* Steps to write Custom Primary Key through Annotation :class SidGenerator{ public static String getNextSid(){}}

Usage(in main) : Student stu=new Student(SidGenerator.getNextSid(),”Krishu”,”Patna”,8888888);

* Using Hibernate SQL Dialects , we can switch any databases without code change. Hibernate will generate appropriate hql queries based on the dialect defined.* Collection types in Hibernate : Bag, Set, List, Array, Map.

* Configure Hibernate SessionFactory for 2 Databasesimport org.hibernate.SessionFactory;import org.hibernate.cfg.Configuration;public class HibernateUtil{

static SessionFactory mysqlSF=null;static SessionFactory oracleSF=null;static {

Configuration cfg=new Configuration();Configuration cfg1=cfg.configure("mysql.cfg.xml");mysqlSF=cfg1.buildSessionFactory();Configuration cfg2=cfg.configure("oracle.cfg.xml");oracleSF=cfg2.buildSessionFactory();

}public static SessionFactory getSessionFactory (int x){

if(x==1)return oracleSF;

elsereturn mysqlSF;

Page 2: Hibernate Complete Overview

}}

* Types of Persistence Object States :

1. Transient State : When Persistence Class is new Created and not participated in any Session Operations then that object is called Transient Object and state of that object is called Transient State. Transient Object does not contain any identity or PK.

2. Persistent State : When Persistent Class object is participated any session operations then that object is called as persistent object. The State of that object is called Persistent State. Persistent Object contains any Identity or Primary Key.

* Any Modification happed on the Persistent Object will be reflected to Database.

3. Detached State : When Persistent class object is participated any session operations and removed from Session Cache then that object is called as Detached Object. The State of that object is called Detached State. Detached object contains any Identity or Primary Key.

Hibernate Annotation : * Hibernate 3 brought a new and elegant configuration approach called Annotations.* Annotations are a mechanisam of passing information about the code spec [class,property,method].* Annotations provide a powerful and flexible way of declaring persistence mappings.* Annotations bassed Mapping are more intuitive than the XML mapping file.* The javax.persistence.*; Package needs to be imported in the Persistence class, where annotations are used.

@Entity - Each and every persistence POJO class is an Entity Bean. The Entity Bean is declared using the @Entity annotation.

@Table - @Table allows specifying the details of the table, which will be used to persist the entity bean in the database. Note : if @Table is not defined, then Hibernate uses the default class name of the entity bean as the table name.

Example : @Table(name="" catalog="")

@Id - Each entity bean must have a primary key, which can be annotated using the @Id annotation.

@Column - The column(s) used for a property mapping can be defined using the @Column annotation. @Column annotation helps specifying

the column details of columns to which a property is being mapped.Example : @Column(name="Username", length=20, updatable=false, nullable=false)

Transaction Management : Transaction is the process of performing multiple database operation as one unit with All-nothing criteria i.e. when all the database operations in the unit are successfully then Transaction is successfully and should be committed. When any one database operation in the unit are failed then Transaction is failed and should be rolled back.A – Atomicity C – Consistency I – Isolation D – Durability

* Transaction Concurrency Problem :--------------------------------------------Dirty Read Problem - cellRepeatable Read Problem - single rowPhantom Read Problem - multiple rows

* Transaction Isolation Level :-------------------------------------READ_UNCOMMITTED - 1READ_COMMITTED - 2 - lock Column - Default Isolation Level (Oracle)REPEATABLE_READ - 4 - lock Row - Default Isolation Level (Mysql)SERIALIZABLE - 8 - lock Table Types of Transaction : 1. Local Transaction 2. Distributed TransactionTypes of Transaction : 1. Flat Transaction 2. Nested Transaction

Specifying Isolation Level in JDBC : con.setTransactionIsolation(1/2/4/8);Get Specifying Isolation Level in JDBC : int getTransactionIsolation(); Get default Isolation Level in JDBC : int getDefaultTransactionIsolation();

Specifying Isolation Level in Hibernate : <property name=”hibernate.connection.isolation”>1/2/4/8</property> (in cfg)

Q. Can I specify different isolation levels for Txs. Running in Hibernate Application = NO (in JDBC - Yes)

Difference between Hibernate and JDBC :Hibernate is a Persistence Framework. JDBC is a Technology Hibernate is database independent. JDBC query must be database specific.Hibernate provides a powerful query language HQL (independent from type of database)

JDBC supports only native SQL.

Hibernate supports automatic versioning of rows. JDBC not supported.Fast development, no need to write sql query. Slow development, write sql query. No need to learn sql only Java needed. Must need sql query.Hibernate supports Cache. So we can store our data into Cache for better performance.

In JDBC, We need to implement our Java cache.

No need to create any Connection pool, we use c3p0. Need to write our connection pool.

Page 3: Hibernate Complete Overview

Hibernate is flexible and powerful ORM solution to map Java classes to database tables. Hibernate itself takes care of this mapping using XML files so developer does not need to write code for this.

 developer has to write code to map an object model's data representation to a relational data model and its corresponding database schema. 

We are responsible to take the required resouces and close the resources after using, if we are not closing the resources that may impact the application performance.

Filter :

hibernate.cfg.xml<hibernate-configuration>

<session-factory><property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property><property name="hibernate.connection.url">jdbc:mysql://localhost/krishu</property><property name="hibernate.connection.username">root</property><property name="hibernate.connection.password">121</property><property name="dialect">org.hibernate.dialect.MySQLDialect</property><property name="show_sql">true</property><property name="hbm2ddl.auto">update</property><mapping resource="com/hibernate/filter/Lab/Customer.hbm.xml"/>

</session-factory></hibernate-configuration>Note in the case of Annotation : <mapping class="com.hibernate.jlcindia.Customer"/>

Hibernate consults hibernate.cfg.xml file for its operating properties such as database dialect,  connection string and mapping files. These files are searched on class path.

customer.hbm.xml<hibernate-mapping package="com.hibernate.filter.Lab" default-lazy="false">

<class name="Customer" table="MyCustomers"><id name="cid" column="cid" type="int">

<generator class="increment"/></id><property name="cname" column=”cname” type=”string”/><property name="status"/><filter name="myStatusFilter" condition=":statusParam=status"/>

</class><filter-def name="myStatusFilter">

<filter-param name="statusParam" type="string"/></filter-def>

</hibernate-mapping>

main()System.out.println("Activated Customers");Filter filter = session.enableFilter("myStatusFilter");filter.setParameter("statusParam", "Active");displayAllCustomers(session);

* Hibernate Mapping :1. Simple Mapping 2. Collection Mapping 3. Inheritance Mapping 4. Association Mapping 5. Other Mapping

# Hibernate Cache S

Page 4: Hibernate Complete Overview

# Configuration / AnnotationConfiguration – (single Threaded and short Lived) – Class – org.hibernate.cfg.Configuration Package* This is the first class that will be instantiated by the Hibernate Application.* main used for 2 tasks :- calling configure() / configure(String); and calling buildSessionFactory(); * configure() method is responsible for (i) reading the data from Hibernate Configuration document.

(ii) reading the data from all the Hibernate Mapping documents specified in the Configuration Document.* buildSessionFactory() method is responsible for creating SessionFactory object.

# SessionFactory – (MultiThreaded and Long Lived) - Interface – org.hibernate.SessionFactory * When we call buildSessionFactory() method on Configuration object then following tasks will happen : @ Set the default to many Parameters like Batch Size, Fetch Size etc.

@ Generates and cached the SQL queries required.@ Select the Connection Provider & Transaction Factory.

* SessionFactory is a factory of Session object.* Client for Connection provider & Transaction Factory.* create one SessionFactory for One Database.

# Session – (SingleThreaded and Short Lived) - Interface – org.hibernate.SessionFactory * Session represents period of time where user can do multiple database operations.* Session object use TransactionFactory to get the Transaction.* Session object get the Connection from Connection provider.

# Transaction – Interface – import org.hibernate.Transaction;* When Transaction is started, then following tasks will happened : 1. Session Cache will be created. 2. Connection will be taken and will be associated with the current session.* While Transaction is running, following tasks will happen : 1. Session will be flushed. 2. Session Cache will be destroyed. 3. Commit will be issued to database. 4. Connection will be realised.

# Criteria# Query#