basics of hibernate
DESCRIPTION
Basics of HibernateTRANSCRIPT
Basics of Hibernate
Agenda
• ORM
• What is Hibernate ?
• Hibernate Architecture.
• Hibernate Installation
• Hibernate Configuration.
• Programming.
• HQL.
• Criteria
• Hibernate Object States
• Caching Techniques in Hibernate
• Advantages of Hibernate over JDBC
ORM ORM
Object-relational mapping (ORM) is a mechanism that makes it possible to access and manipulate objects without having to consider how those objects relate to their data sources.
Persistent Framework A persistence framework is a tool for simplifying
the development and maintenance of object systems. Hibernate is considered as a persistent framework for Java!So why do we need a persistence framework?
- To avoid hard coding SQL into our Java applications
What is Hibernate?
• Hibernate is an object-relational mapping (ORM) library for the Java language, providing a framework for mapping an object-oriented domain model to a traditional relational database.
• Hibernate solves object-relational impedance mismatch problems by replacing direct persistence-related database accesses with high-level object handling functions.
Features
• Mapping from Java classes to database tables (and from Java data types to SQL data types).
• Data query and retrieval facilities.
• Generates the SQL calls and relieves the developer from manual result set handling and object conversion
• Portable to all data bases
• Provides persistence for Plain Old Java Objects(POJO)
Why should you use it• Hibernate generates query called HQL• Data base independent• Supports OO concepts like, Inheritance and
Polymorphic mappings• HQL is gives optimal query and gives more
performance• No specific container needed• Hibernate components are not distributed• Can't be invoked remotely
Hibernate ArchitectureApplication
(Hibernate)
Configuration
Session Factory
Session Transaction Query Criteria
JTA JDBC JNDI
Database
Persiste
nt
Ob
jects
Hibernate Architecture(Contd..)
9
Hibernate - Instalation Pre-requisites
• JDK 1.4 or above• SQL Database and JDBC libraries• Web/App Server (If development is Web-based)
Steps to install1. Place the Hibernate Jar and Dependant jars in the
Classpath.2. Place the JDBC jar in the classpath3. Configure Hibernate using Property file4. Create Persistance Objects (Simple POJOs)5. Create ORM Mappings in XML as per hibernates
specification.
10
Hiberbate – Jars
antlr.jar cglib.jar asm.jar asm-attrs.jars commons-collections.jar commons-logging.jar hibernate3.jar jta.jar dom4j.jar log4j.jar
11
Hibernate - Programming Model
entity.hbm.xml
POJOPersistence
Class
Hibernate-cfg.xml
DB
12
It is simple Java Class with getters and setters.
An entity can be described with it is functionality (methods) and properties (fields)
POJO gets and sets values to Database filed thru Persistence class.
Hibernate – POJO
13
Sample POJO
public class Message { private Long id; private String text;
Message() {}
public Long getId() { return id; } private void setId(Long id) { this.id = id; } public String getText() { return text; } public void setText(String text) { this.text = text; }}
14
Hibernate Configuration file
Hibernate-cfg.xml is an XML file which contains configuration information about Database driver, URL , and access credentials etc.
Easy to change database by altering the configuration file.
In an application can have more than one configuration file if it is needed.
15
Hibernate –CFG file<hibernate-configuration><session-factory>
<property name="hibernate.connection.driver_class">org.hsqldb.jdbcDriver</property>
<property name="hibernate.connection.url">jdbc:hsqldb:hsql://localhost</property>
<property name="hibernate.connection.username">sa</property>
<property name="hibernate.connection.password">sa</property>
<property name="hibernate.dialect">org.hibernate.dialect.SybaseDialect</property>
<mapping name=“MapResources" > /WatermarkContent.hbm.xml </mapping></session-factory></hibernate-configuration>
16
Hibernate –Mapping XML.
This XML file maps the POJO member fields in to corresponding database table and fields.
To mange the primary key (auto increment etc) , need to specify generator class tag.
17
Hibernate Mapping File
<hibernate-mapping>
<class name=“hibernate.Message" table="MESSAGES" schema="PUBLIC">
<id name="id" type="long"> <column name="MESSAGE_ID" /> <generator class="increment"></generator> </id>
<property name="text" type="string"> <column name="MESSAGE_TEXT" /> </property> </class>
</hibernate-mapping>
18
Hibernate – Generator Tags
Generator Tags
–Increment–Identity –Sequence–Hilo –Seqhilo –uuid –guid –Native–assigned –Select–foreign
Hibernate- Java Classpublic class HibernateExample {
Configuration cfg = new Configuration();
cfg.configure();
SessionFactory sessionFactory = cfg.buildSessionFactory();
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
Message msg= new Message(); // POJO
msg.setTitle(title);
msg.setDate(theDate);
session.save(msg); // insert into
tx.commit();
session.close();
} 19
20
Hibernate- MethodsSingle Row:
******************************************* session.load(AuctionItem.class, id); // SELECT*******************************************Multiple rows:
Criteria crit = session.createCriteria(AuctionItem.class); crit.setFetchSize(50); List items = crit.list(); // select * from table_name
*******************************************session.delete(items ); // delete from … *******************************************session.update(items );*******************************************session.saveOrUpdate(items );*******************************************
To Save it in DB:Transaction.commit() (OR)Session.flush()
21
HQL
Make SQL be object oriented• Classes and properties instead of tables and columns• Much less verbose than SQL
Full support for relational operations• Inner/outer/full joins, cartesian products• Projection• Aggregation (max, avg) and grouping• Ordering• Subqueries• SQL function calls
22
Hibernate - HQL
select * from Salary // In Java
from Salary // HQL
SessionFactory factory = new Configuration(). configure(). buildSessionFactory();
Session session = factory.openSession();Query query = session.createQuery(“from Salary”);List allActions = query.list();
23
Criteria Query API
1. Criteria 2. Criterion 3. Restrictions 4. Projection 5. Order
24
Criteria - Methods
Methods
• add• addOrder ----- addOrder( Order.asc("age") ) • createAlias ---- .createAlias(“Books", “notes") • createCriteria ---- .createCriteria(“studentmarks") • setFetchSize • setFirstResult• setMaxResults• uniqueResult
25
Criteria – Applying RestrictionsCriteria Query:
Criteria crit = session.createCriteria(SavingsAccount.class); crit.add(Expression.between(“BalanceAmount", new Integer(1000), new Integer(2500))); //Between condition crit.setMaxResults(5); //Restricts the max rows to 5
SavingsAccount saveAcns = crit.list(); for(Iterator it = saveAcns.iterator();it.hasNext();){ SavingsAccount sa = (SavingsAccount) it.next(); System.out.println("ID: " + sa.getSavingsId()); System.out.println("Name: " + sa.getAccHolderName());
Equivalent HQL:Query query = session.createQuery(from SavingsAccount sa where sa.balanceAmount between new Integer(1000) and new Integer(2000))
26
Criteria Ordering
Criteria criteria = session.createCriteria(Student.class)
criteria.addOrder(Order.desc(“Stud_name"))
List books = criteria.list();
HQL:
Query query = session.createQuery (from Student order by Stud_name desc;)
27
Criteria Grouping
Criteria criteria = session.createCriteria(Student.class)criteria.add(Projections.groupProperty(“passedOutYear"))criteria.add(Projections.avg(“marks"))List books = criteria.list();
SQL:
select student.passedOutYear, avg(student.marks)from Student studentgroup by student.passedOutYear
28
Criteria – Applying Restrictions
Criteria criteria = session.createCriteria(Topics.class)criteria.add(Restrictions.or(Restrictions.like("name", "%Hibernate%"),Restrictions.like("name", "%Java%")))criteria.add(Restrictions.between(“credit", new Integer(100), new Integer(200)));List topics = criteria.list();
Hibernate Object States
Transient - an object is transient if it has just been instantiated using the new operator and it is not associated with a Hibernate Session
Persistent - a persistent instance has a representation in the database and an identifier value. It might just have been saved or loaded.
Detached - a detached instance is an object that has been persistent, but its Session has been closed.
Hibernate Object States
Transient
Persistent
Detached
new
load
save/ saveorupdate
delete
evict, close, clear
saveorupdate, lock, update
Garbage Collector
Caching Techniques in Hibernate
Hibernate uses two different caches for objects: first-level cache and second-level cache..
• First-level cache: First-level cache always Associates with the Session object.
• Second-level cache: Second-level cache always associates with the Session Factory object.
Advantages of Hibernate over JDBC
1) Hibernate is data base independent, same code will work for all data bases like ORACLE,MySQL ,SQLServer etc.In case of JDBC query must be data base specific.
2) As Hibernate is set of Objects , you don't need to learn SQL language.You can treat TABLE as a Object . In case of JDBC you need to learn SQL.
3) Don't need Query tuning in case of Hibernate. If you use Criteria Quires in Hibernate then hibernate automatically tuned your query and return best result with performance.In case of JDBC you need to tune your queries.
4) You will get benefit of Cache. Hibernate support two level of cache. First level and 2nd level. So you can store your data into Cache for better performance.In case of JDBC you need to implement your java cache .
Advantages of Hibernate over JDBC(Contd..)
5) Development fast in case of Hibernate because you don't need to write queries.
6) No need to create any connection pool in case of Hibernate. In case of JDBC you need to write your own connection pool.
7) In the xml file you can see all the relations between tables in case of Hibernate. Easy readability.
8) You can load your objects on start up using lazy=false in case of Hibernate.JDBC Don't have such support.
Some Important Concepts•Lazy Loading --Getting the objects when needed
•Eager Loading – Getting it the first time when you hit the database
•Difference between load and get methods
•Load() --- Retrieves the objects from the Persistence Context , only if not available, database will be hit.
•Get() – Retrieves from database.
• Persistence Context ( Maintains cache of retrieved objects)
• SessionFactory( Thread safe) & Session (Not thread safe)
• Object states and lifecycle
Transient, Persistent, Detached, Removed
35
Reading Material
http://www.hibernate.org
Hibernate from Manning Publications(Previously “Hibernate in Action”)
36
References http://www.hibernate.org/hib_docs/annotations/reference/en/
html_single/
http://www.java2s.com/Code/Java/Hibernate/CascadeSaveOrUpdate.htm
http://www.devarticles.com/c/a/Java/Hibernate-Criteria-Queries-in-Depth/1/
ANY Questions ?Thank You