Tuesday, May 21, 2013

Hibernate(Object Relational Mapping) and working of hibernate


Hibernate:

Hibernate is one of the commonly used ORM tool to deal with database. Hibernate is a framework (software) to be used in applications that deals with database. 

What is ORM:

ORM refers to Object Relational Mapping i.e, Mapping the java objects with the corresponding relational records in the database.

Advantages over jdbc:

As we have jdbc to deal with database,but  hibernate will have more advantages than jdbc.

--> Use of hibernate will improve the productivity (less amount of code compared to jdbc)

--> Hibernate provides relations like one to one , one to many, many to one and many to many

-->  Hibernate comes with HQL ( hibernate query language), which is database independent. So we can deal with any database without changing the code.

--> If we use hibernate, no need to configure connection pool (c3p connection pool will be bundled with hibernate)

--> Hibernate supports two levels of cache (first level and second level) which improves the performance of the application.

--> In hibernate , exceptions that occur are unchecked exceptions where as in jdbc , checked exceptions will be caught and thrown by try catch.

Note:

According to the hibernate documentation, hibernate may not be the best solution for data centric applications which uses stored procedures for buisiness logic. 

Hibernate gives best result for the applications which have buisiness logic as part of java classes instead of stored procedures.


Hibernate Architecture:


As shown pictorially, java application with hibernate api code will communicate with hibernate software which will connect to the database.

Components of Hibernate:

Hibernate mainly consists of three components. They are

--> Hibernate configuration file

--> Hibernate mapping file

--> Pojo classes

Hibernate Configuration file:

A configuration file is an xml file contains the configuration details like driver class name, url, user name and password to connect with database. It also includes the mapping file information

syntax:


A hibernate application contains one configuration file with one or more mapping (hbm) files.

Hibernate mapping file: 

A mapping file (hbm) shows which table is mapped with which pojo class, and mapping the properties of pojo classes with columns of tables.

syntax: 


A Hibernate application can have one or more mapping files. We can map multiple pojo classes with tables by using <class> .

It's recommended to write seperate hbm (mapping) files for each table and pojo class.

Number of mapping files, pojo classes depends on number of tables in the database.

Pojo class:

A POJO (plain old java object) is a normal java bean with couple of setters, getters and/ or some additional methods.

syntax: 



Sample Hibernate application:

Create a java project HibernateSampleApp , add the hibernate capabilities( hibernate jar's ) to the project build path and as discussed earlier we need to have the following files.

A Hibernate Configuration file.




and Hibernate mapping file Student.hbm.xml


and a pojo class Student.java


Now create a main class SampleHibernateApp with main()



If we run the above application, we can found a table with name student in database with columns id, student_name.

As we have defined an extra property in hibernate.cfg.xml, hbm2ddl.auto will create the tables if not exists.

If it's values is update it will update the table if already exists , otherwise it will create the table in database.

show_sql property will show  the query sent to the database in console.


What's happening when we run the application:

When we run the SampleHibernateApp, hibernate will start execution by creating a Configuration object. Immediately hibernate software will call configure() which is an expensive method.

when configure() got called, hibernate will load the configuration file (hibernate.cfg.xml) into jvm's memory and will check for the properties mentioned.

 As we have defined mapping file information in configuration file, hibernate will also loads the mapping file into jvm memory and checks for the appropriate tables in database. If not exists, if we have given hbm2ddl.auto property, hibernate will create the required tables.

So calling configure() takes so much of time to do all these tasks. That's why hibernate specification says we should call configure() only once through out the life time of a project.

Once we have configuration object we can get SessionFactory object by using buildSessionFactory().

When buildSessionFactory() called, hibernate will try to connect with database with the information already stored in jvm memory ( from cfg and hbm files) and will create some basic queries for inserting, updating, deleting and retrieving and stores those queries in jvm memory.

buildSessionFactory() is also an expensive method since lot of task is going behind. We should call this only once through out the project.

A SessionFactory is an interface which can hold a bunch of Session objects.
Once we got SessionFactory we can get session object by calling openSession() which will get's the connection from database.

beginTransaction() will enable the transactions with database.

When we create object to our pojo class Student, the instance variables were initialised with default values initially (0 for int, null for string /advanced data types).

Calling setters will assign the values that we specified to the student object.

Calling session.save() will not send an insert query to the database. The student object will be associated with session object when we call save(). 

When we call commit() hibernate will check in the first level cache ( which will be created at the time of creating session object ) whether any object is associated (attached) to the session object with some code and will get the class name from object (student.getClass()).

 As hibernate already read the cfg,hbm files and stored in jvm, from that information it will get the table to which it has to send the query.

Finally , hibernate will picks the insert query that was already stored in jvm memory based on some internal registration code and will send that query to the database.

We should close the session so that the connection from the database will be given back.

Note:

Using hibernate in web based applications along with spring explained here


Wednesday, May 15, 2013

JSTL (Jsp Standard Tag Library) tags and their use

With the introduction of custom tags to remove the java code from jsp, every vendor can develop their own tags. But the problem is that, for every project in every organisation some common requirements will exists. For those, it's waste of time to develop own tags by every vendor. Instead of that Sun itself has given commonly used tags to use in our applications.

JSTL:

JSTL refers to Jsp Standard Tag Library and is a custom tag library released by Sun Micro Systems.

JSTL comes with different set of groups of tags. They are

core Tag library,
fmt tag library,
sql tag library and
xml tag library

Core Tag Library:

If we want to use core tag library in our jsp instead of java code, we need to include the tag library as shown.


prefix attribute can take any characters to use the tags in jsp. uri attribute specifies the uri of the corresponding tag library, add the jstl jar in the lib folder.

As part of Core tag library the following tags are bundled.

set:

<c:set> is used to set a value into a specific scope or to set the result of an expression into a specific scope.

syntax:


value attribute allows any value or result of any expression as shown above.
scope can be any of page, request, session and application.

redirect:

<c:redirect> is used to redirect to a specified location. Instead of response.sendRedirect() ( java code ) we can use <c:redirect>.

syntax:


url attribute specifies the location to which it has to be redirected.


out:

<c:out> is used to display the contents to the user (on the browser).Instead of out.println() (java code) we can use <c:out> in jsp.

syntax:


value attribute specifies the value to be rendered on the browser, default attribute will take the default value to be display if the resulting value is null.

catch:

<c:catch> is used to catch the exception thrown in its body.

syntax:


var attribute specifies the name of the scoped variable for the exception thrown.

if:

<c:if> is the simple conditional tag to check conditions in jsp.

syntax:


test is the required attribute here, which allows a condition check , and executes the if body incase of condition is true.

var is the name of the variable for the condition result and of type boolean (true for condition true and false for condition fail)


choose:

<c:choose> is the simple conditional tag which has child tags <c:when> and <c:otherwise>

syntax:


when:

when the condition given in the <c:choose> is true it's body will be executed , if condiction fails it will skip executing body and go for <c:otherwise>. test is the mandatory attribute where we will provide condition.

otherwise:

when condition fails in the <c:when>, then the <c:otherwise> body will be executed just like if ,else in java code.

forEach:

To perform the iterations, we will take the help of <c:forEach> which acts as for loop in jsp.

syntax:


begin and end specifies the starting and ending value of the loop to iterate and step specifies the incremental value from starting. if we have not given begin and end,and if we mentioned the items attribute to iterate over collection elements, index always starts from 0.

forTokens:

<c:forTokens> is used to iterate over set of tokens seperated by delimeter

syntax:


items specifies collection of items seperated by delimeter. here @ is considered as delimeter , we can use any character as delimter (including space).

import:

<c:import> is used to import the contents from specified url (just like jsp:include)

syntax:


or if we want to include html content also we can use like this,



url:

To create url with optional parameters we will use <c:url>

syntax:


with the given var name we can access the url in the jsp later.


param:

<c:param> is used to add parameters to the url that will be given to import tag

syntax:


The parameters mentioned will be appended to url while importing.


remove:

to remove a specific scoped variable from a specific scope <c:remove> will be used.

syntax:


after removing from specified scope, if we try to access that variable we will get null as it was removed from the scope.


fmt tag library:

fmt (formatting) tags used to format the text, numbers, date based on the locale (internationalization).

To use fmt tag library we need to include taglib,



some mostly used tags are., 

message:

this tag is used to retrieve the message from property file based on the key and bundle

synatx:


formatDate and formatNumber:

Used to format given date and number based on supplied style/ pattern.

syntax:



Similar way the other tags u can go through from the link.


Sql tag library:

sql tag library is used to deal with database opeartions. To set the datsource we have <sql:setDataSource>, to execute a query <sql:query>.

To Executes the SQL update defined in its body we can use <sql:update>


Note:

As per MVC design pattern, we should not write dao logic in jsp. So in general we will not use these tags at all.


Xml tag library:

xml tag library is used to deal with xml documents and almost all tags available as part of xml tag library are same as core tag library.

You can go through this link.

Download the source and observe the working behaviour of all tags.


Monday, May 13, 2013

Jsp Action, Custom tags and EL expressions

To remove the java code from jsp, Sun micro system has given jsp action tags.

Jsp Action tags:

The following are the jsp action tags to use as part of a jsp.

--> <jsp:include/>
--> <jsp:forward/>
--> <jsp:useBean/>
--> <jsp:setProperty/>
--> <jsp:getProperty/>


<jsp:include/>

is used to include the contents of two jsp's and send the result to the client (browser).

syntax:


'page' attribute specifies the name of the jsp to which the content from the calling jsp has to be included.

When ever jsp compiler has encountered the , it will evaluate the tag (convert the tag into corresponding servlet code) and includes the content of two jsp's.


<jsp:forward/>

is used to forward a request from one resource to another resource (like RequestDispathcer). Instead of java code (RequestDispatcher) in jsp , we can use and   to include and forward the request.

syntax:


'page' attribute specifies the resource (jsp or html or servlet) to which the request has to be forwarded.

When evre jsp compiler has encountered the it will evaluate the tag and forwards the request to corresponding resource given to the path attribute.


<jsp:useBean/>

Create a java bean 'SampleBean' with two properties name and rollno.


Now, if we want to create object to this java bean as part of our jsp, as we know we should not write java code in jsp (like SampleBean bean = new SampleBean() ), we will take the help of

syntax:


class attribute specifies name of the class to which object has to be created, id attribute specifies unique id to the created object to use it further and the scope attribute specifies type of scope (page/request/session/application).

When ever jsp compiler encountered the , it will evaluates the tag and get's the class from class attribute and container will create object with the given id within the given scope.

<jsp:setProperty/>

is used to set the value of a property specified in corresponding java bean.

syntax:


property attribute specifies the name of the property in the java bean (name here), name attribute specifies name (id) of the bean object (sampBean) and value attribute specifies the value given to the property('addicted' here).

Whenever jsp compiler encountered the it will evaluates the tag to corresponding servlet code and checks the name of property in the java bean and set's the value supplied to the value attribute.


<jsp:getProperty/>

is used to get the property value from the corresponding java bean specified.

syntax:


property attribute specifies the name of the property in the java bean, name attribute specifies the name(id) of the bean object.

Jsp compiler will evaluates the tag ,get's the value of the property from the java bean and displays in the browser.


Jsp Action tag's are sufficient ..?

To avoid the java code from the jsp , jsp action tags are not sufficient. If we use action tags we can't remove some java code like jsp expressions(<%= =>) .That's why concept of custom tags came into the picture.


Jsp Custom Tags:

Custom tags are the user defined tags, which can be used to remove the java code as part of jsp.

We can also create our own tags by following some rules.

Create your own custom tag:

If we want to create our own custom tags, we need to have the following.

--> a tld( taglib directive) file and
--> a jar file consisting of the tag handler classes

creating tld file:

To create the tld file, we need to follow the jsp custom tag specification. The following is the custom tld file we have created.


<taglib> is the root tag which has child tags like <tlib-version>,<uri>,<tag> etc.

Each <tagelement has child tags like <name><tag-clas>,<attribute> etc.

creating Tag Handler class: 

A tag handler class is a class which provides the implementation of javax.servlet.jsp.tagext.Tag interface directly or indirectly.

If our class is implementing javax.servlet.jsp.tagext.Tag interface, everytime we need to override some couple of methods repeatedly as shown.


Instead of implementing all the methods, Sun microsystem itself has given a predefiend class javax.servlet.jsp.tagext.TagSupport implementing Tag interface.

So if we create a class extending javax.servlet.jsp.tagext.TagSupport it will become tag handler class.


PerformTaskTagHandler is the custom tag handler class which has a property text, since we have only one attribute text ,for the tag perfom in the tld file.

Number of properties in the tag handler class depends on the number of attributes to that class in tld file.

To use the custom tag library in our application we can take the help of taglib directive.


uri attribute specifies the resource location( tld location), whatever uri we specify in tld file, that has to be mentioned in uri attribute.

prefix attribute is used to use the tag as part of our jsp as shown above.

Once the tag got evaluated by jsp compiler, the corresponding tag handler class PerformTaskTagHandler  will be called and doEndTag() will be executed.

In doEndTag() we are returning int value as EVAL_PAGE. We can also return it as SKIP_PAGE.

EVAL_PAGE refers to once doEndTag() got executed ,jsp compiler will evaluate the remaining tags in the jsp.

SKIP_PAGE refers to , after execution of doEndTag() jsp compiler will skip all the tags without evaluating.

Whatever the task we want to perform with the help of our custom tag, we will write code to that task as part of doEndTag().


EL Expressions:

EL (Expression Language) expressions are used to deal with scopped variables.


Scopped variables:

A variable with a specific scope is called scopped variable. we have four different scopped variables available.

They are :

--> Page scope
--> Request scope
--> Session scope and
--> Application scope

The scope (availability) of page scope is within that page only. The scope of request scope is within that request that is executing. 

The scope of session scope is with in that browser for any request.
The scope of application scope is within that application from any browser and any request.

Suppose we want to deal with scopped variables as part of jsp, instead of writing java code like out.println(request.getAttribute("keyname")), we can take the help of EL expressions.

syntax:


simply use ${} to use EL expressions. Here, sampBean is the name of the object which was stored in reuest scope.

Whenever jsp compiler encounters EL expressions it will check for the key(sampBean) in scopes folloeing this order page,request,session,application.

If it founds key (sampBean) in page scope it will stop searching in remaining scopes.

Or if we know in which scope the key was available we can directly give


Now jsp compiler will only check in request scope.

pageScope ,
requestScope,
sessionScope and
applicationScope are the implicit objects avaialable in jsp to deal with scopped variables.

In order to use the EL expressions in jsp we need to make sure that isElIgonred attribute to false.