You are on page 1of 63

Introduction to Hibernate

By
Sandeep(CITI)
Copyright 2012 Tata Consultancy Services Limited

Introduction

It is an ORM Tool

Used in Data layer of the Application

Implements JPA

Why we have to use ORM Tool

Problems with JDBC

Mapping Member variable to columns

Mapping relationships

Handling Data types

Object Relational Mapping

ORM is a programming method to map the objects in java with


the relational entities in the database.
In this,entities/classes refers to table in database,instance of
classes refers to rows and attributes of instances of classes
refers to column of table in database.
This provides solutions to the problems arise while developing
persistence applications using traditional JDBC method.

Hibernate Architecture

Configuration Object

The Configuration object is the first Hibernate object you create


in any Hibernate application and usually created only once
during application initialization.
The Configuration Object has two Components
i)Database Connection :This is handled through
hibernate.properties or hibernate.cfg.xml

ii)Class Mapping Set up:This component creates the


connection between the Java classes and database tables

SessionFactory Object

Configuration object is used to create a SessionFactory object


which in turn configures Hibernate for the application using the
supplied configuration file and allows for a Session object to be
instantiated.
The SessionFactory is a thread safe object and used by all the
threads of an application.
The SessionFactory is heavyweight object so usually it is
created during application start up and kept for later use.
You would need one SessionFactory object per database using
a separate configuration file.
So if you are using multiple databases then you would have to
create multiple SessionFactory objects.
8

Session 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 Session
object
Session Objects should be created or destroyed them as
needed

Required Things

i)Hibernate.cfg.xml

ii)Class Mapping Files

iii)POJO Class

iv)Test Class

10

POJO Class

11

Hibernate.cfg.xml

12

Class Mapping File

13

Test Class

14

Cache in Hibernate

Caching is a facility provided by ORM frameworks which help


users to get fast running web application, while help framework
itself to reduce number of queries made to database in a single
transaction.
There are three types of Cache in Hibernate
i)First level Cache
ii)Second level Cache
iii)Query level Cache

15

First Level Cache

First level cache is associated with session object and other


session objects in application can not see it
The scope of cache objects is of session. Once session is
closed, cached objects are gone forever.
First level cache is enabled by default and you can not disable
it.
When we query an entity first time, it is retrieved from database
and stored in first level cache associated with hibernate session
If we query same object again with same session object, it will
be loaded from cache and no sql query will be executed.

16

Example for First Level Cache

17

Example for First Level Cache

18

Second Level Cache

This is apart from first level cache which is available to be used


globally in session factory scope
Second level cache is created in session factory scope and is
available to be used in all sessions which are created using that
particular session factor.
It also means that once session factory is closed, all cache
associated with it die and cache manager also closed down.
Whenever hibernate session try to load an entity, the very first
place it look for cached copy of entity in first level cache
(associated with particular hibernate session).

19

Second Level Cache

If cached copy of entity is present in first level cache, it is


returned as result of load method.
If there is no cached entity in first level cache, then second level
cache is looked up for cached entity.
If second level cache has cached entity, it is returned as result
of load method. But, before returning the entity, it is stored in
first level cache .
If unable to find Entity in first and second level cache hibernate
will fetch the data from database

20

Example for Second Level Cache

21

Example for Second Level Cache

22

Query Cache

Hibernate caches the query result ,which is frequently used.

This is useful if we are executing same queries again and again

23

Query Cache

Set hibernate.cache.use_query_cache property to true


Set Cacheable to True

24

First Look at HTML5


Remember the DOCTYPE declaration from HTML4.0.1?
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">

In HTML5, there is just one possible DOCTYPE declaration and it is simpler:


<!DOCTYPE html>

Just 15 characters!

The DOCTYPE tells the browser which type and version of document to
expect.
25

First Look at HTML5


Remember the Charset Encoding inHTML4.0.1?
<meta http-equiv="Content-Type" content="text/html;charset=ISO-8859-1">

Simplier in HTML 5
<meta charset="UTF-8">

Char set attribute

26

Aim Of HTML5

Reduce the need for external plug-in and


scripts to show website content
Improve the semantic definition (i.e.
meaning and purpose) of page elements.

27

Main Features of HTML 5

Semantics

Forms

Audio and Video

Geolocation

Web Storage
Server Sent Events

28

What are Semantic Elements in HTML 5

Semantic elements are elements with a meaning


A semantic element clearly describes its meaning to both the
browser and the developer.
Examples of non-semantic elements: <div> and <span> - Tells
nothing about its content.
Examples of semantic elements: <form>, <table>, and
<img>,<body> - Clearly defines its content.
HTML 5 defines new set of Semantic elements

29

Semantic Elements in HTML 5


<article>

<aside>

<details>

<header>

<footer>

<time>

<section>

<nav>

30

Semantic Elements

Semantic elements are elements with a meaning


<nav>: Represents a major navigation block. It groups links to
other pages or to parts of the current page.
<nav> can be used For instance, footers often contains links to
terms of service, copyright page and such,

<nav>

<a href="/tcs/">TCS</a>

<a href="/event/">Events</a>

<a href="/contact us/">Contact Us</a>

</nav>
31

Semantic Elements

The <header> element specifies a header for a document or


section

You can have several <header> elements in one document

<header>

<h1>Welcome to HTML 5 Session</h1>

<p>Start learning HTML 5</p>

</header>

32

Semantic Elements

The <footer> element specifies a footer for a document or


section

You can have several <footer> elements in one document

<footer>

<p>Conducted by:Sandeep</p>

<p>Contact information: <a href="sandeep@tcs.com">

contact</a>.</p>

</footer>

33

Semantic Elements

The <section> element used for grouping together thematicallyrelated content

The <section> tag defines sections in a document, such as


chapters, headers, footers, or any other sections of the
document.
<section>

<h1>WWF</h1>

<p>The World Wide Fund for Nature (WWF) is....</p>

</section>

34

Semantic Elements

The <header> element specifies a header for a document or


section

You can have several <header> elements in one document

<header>

<h1>Welcome to HTML 5 Session</h1>

<p>Start learning HTML 5</p>

</header>

35

Semantic Elements

The <article> element specifies independent, self-contained


content
Article element can be nested in another "article" element.
An article element doesn't just mean article content. You can
have header and footer element in an article.

<article>

<p>My First Article</p>

</article>

36

HTML 4 vs. HTML 5

37

HTML 5 Forms

HTML5 web forms have introduced new form elements, input


types, attributes, and other features
The difference is that where before we had to resort to
JavaScript to create these behaviors, theyre now available
directly in the browser
All you need to do is set an attribute in your markup

38

HTML 5 Forms

HTML5 gives us input types that provide for more data-specific


UI elements and native data validation.

HTML5 has a total of 13 new input types:

Search,email,url,tel,datetime,date,month,week,time,

Number,range,color,datetime-local

Example:<input type="email" name="usermail" />

<input type="date" name="currentDate" />

<input type="color" name="favouriteColor" />

39

HTML 5 Form Attributes

Auto complete

Required

Pattern

Maxlength,Minlength

Title

Placeholder

Autofocus

Novalidate

40

Form Elements

<input id="cc" type="text" pattern="[a-zA-Z0-9]{5,9}" required


size="30" title="Minimum 5 letters or numbers."/>

41

Audio and Video

One of the most exciting buzz these days in web circles is about
HTML5 and specifically video on HTML5. HTML5 video tag has
solved the age old problem site owners and designers face on how to
best embed video on websites.
Prior to the new HTML5 video tag you basically had two options for
embedding video on your site to get a video player or to use a 3rd
party service like YouTube to host your video and then use their
embed code to put the video on your site.
Most people are currently using the 2nd option of using services like
YouTube to host their videos and them embedding them on their own
site.

42

Audio and Video Tags


<video width="550" height="320 autoplay controls="controls" >
<source src="E:\songs\video songs\Myvideo.mp4"
type="video/ogg" />
Your browser does not support the video tag.
</video>

<audio src=MyAudio.mp3" autoplay controls="controls">This is


alternate text that is seen if the users browser does not recognize the
html5 tag</audio>

43

Audio and Video

Autoplay

Autoplay

Controls

Controls

Loop

Muted

Muted

Src

Src

Height

Width

Poster

44

Video and Audio

Video

Audio

45

Geo Location
The Geolocation API of HTML5 helps in identifying the users location,
which can be used to provide location specific information or route
navigation details to the user.

Techniques used for tracking are

i)IP-based or

ii)GPS

iii)Cell tower

Geolocation API protects user privacy by seeking permission from the


user before sending the location information to the website.

46

Geo Location
With geo location, you can determine the users current position. You can
also be notified of changes to their position, which could be used, for
example, in a web application that provided real-time driving directions.

Geolocation: methods
These different tasks are controlled through the three methods
currently available
i)getCurrentPosition
ii)watchPosition
iii)clearPostion

47

GeoLocation

The current location of the user can be obtained using


the getCurrentPosition function of the
navigator.geolocation object.
This function accepts two parameters Success call back
function, Error call back functions

navigator.geolocation.getCurrentPosition(showPosition ,Error);

showPosition function returns the position of the user.

Error function does the Error Handling mechanism if any error


occurred

48

GeoLocation

function getLocation() {
if (navigator.geolocation) {

navigator.geolocation.getCurrentPosition(showPosition);

}
function showPosition(position) {

x.innerHTML = "Latitude: " + position.coords.latitude +

"<br>Longitude: " + position.coords.longitude;

49

Geo Location

function showError(error) {
switch(error.code) {
case error.PERMISSION_DENIED:
x.innerHTML = "User denied the request for
Geolocation.";
break;
case error.POSITION_UNAVAILABLE:

x.innerHTML = "Location information is unavailable.";

break;

50

GeoLocation

51

Geolocation

52

Web Storage

Cookies were invented early in the webs history, and indeed


they can be used for persistent local storage of small amounts
of data.
But they have below potentially downsides
i)Cookies are included in every HTTP Request
ii)Cookies are limited to 5 KB

53

Cookies Disabled

54

Web Storage

The Web Storage API defines a standard for how we can save
simple data locally
With Web Storage, we now have a standardized definition for
how to store up to 5MB of simple data created by our websites
or web applications
Web Storage is a great complement to Offline Web
Applications, because you need somewhere to store all that
user data while youre working offline,

55

Web Storage

Simply put, its a way for web pages to store named key/value pairs locally,
within the client web browser.

Unlike cookies, this data is never transmitted to the remote web server (unless
you go out of your way to send it manually)
HTML local storage provides two objects for storing data on the client:

window.localStorage - stores data with no expiration date


code.sessionStorage - stores data for one session (data is lost when the tab is
closed)

56

Web Storage

57

Web Storage

getItem( String key);

void setItem(String key, String value);

removeItem(String key);

Clear()

58

Server Sent Events

A server-sent event is when a web page automatically gets


updates from a server
Server-Sent Events are real-time events emitted by the server
and received by the browser.
Theyre similar to Web Sockets in that they happen in real time,
but theyre very much a one-way communication method from
the server
Example:Stock price Updates,news feeds, Scorecards etc.

59

Server Sent Events

60

Main Points of interest

New EventSource(url)

Onopen-When the connection to the server is opened,

Onmessage- When the message is received

Event.data-Actual String Message sent by the server

CloseCloses the connection from client side

61

Server Sent Events

62

Queries

63

You might also like