Jul 31, 2009

Basic Architecture of Hibernate

Introduction to Hibernate:

Hibernate is an Object-Relational Mapping (ORM) solution for JAVA. It is a powerful, highperformance object/relational persistence and query service. It allows us to develop persistent classesfollowing object-oriented idiom – including association, inheritance and polymorphism.


Hibernate Architecture

1) itself opens connection to database,

2) converts HQL (Hibernate Query Language) statements to database specific statement,

3) receives result set,

4) then performs mapping of these database specific data to Java objects which are directly used by Java application.

Hibernate uses the database specification from Hibernate Properties file. Automatic mapping is performed on the basis of the properties defined in hbm XML file defined for particular Java object.



JDBC Vs Hibernate

Why is Hibernate better than JDBC

1) Relational Persistence for JAVAWorking with both Object-Oriented software and Relational Database is complicated task withJDBC because there is mismatch between how data is represented in objects versus relationaldatabase. So with JDBC, developer has to write code to map an object model's data representationto a relational data model and its corresponding database schema. Hibernate is flexible andpowerful ORM solution to map Java classes to database tables. Hibernate itself takes care of thismapping using XML files so developer does not need to write code for this.

2) Transparent PersistenceThe automatic mapping of Java objects with database tables and vice versa is called TransparentPersistence. Hibernate provides transparent persistence and developer does not need to write codeexplicitly to map database tables tuples to application objects during interaction with RDBMS.With JDBC this conversion is to be taken care of by the developer manually with lines of code.

3) Support for Query LanguageJDBC supports only native Structured Query Language (SQL). Developer has to find out theefficient way to access database, i.e to select effective query from a number of queries to performsame task. Hibernate provides a powerful query language Hibernate Query Language(independent from type of database) that is expressed in a familiar SQL like syntax and includesfull support for polymorphic queries. Hibernate also supports native SQL statements. It also selectsan effective way to perform a database manipulation task for an application.

4) Database Dependent CodeApplication using JDBC to handle persistent data (database tables) having database specific codein large amount. The code written to map table data to application objects and vice versa isactually to map table fields to object properties. As table changed or database changed then it’sessential to change object structure as well as to change code written to map table-to-object/objectto-table. Hibernate provides this mapping itself. The actual mapping between tables andapplication objects is done in XML files. If there is change in Database or in any table then theonly need to change XML file properties.

5) Maintenance CostWith JDBC, it is developer’s responsibility to handle JDBC result set and convert it to Java objectsthrough code to use this persistent data in application. So with JDBC, mapping between Javaobjects and database tables is done manually. Hibernate reduces lines of code by maintainingobject-table mapping itself and returns result to application in form of Java objects. It relievesprogrammer from manual handling of persistent data, hence reducing the development time andmaintenance cost.

6) Optimize PerformanceCaching is retention of data, usually in application to reduce disk access. Hibernate, withTransparent Persistence, cache is set to application work space. Relational tuples are moved to thiscache as a result of query. It improves performance if client application reads same data manytimes for same write. Automatic Transparent Persistence allows the developer to concentrate moreon business logic rather than this application code. With JDBC, caching is maintained by handcoding.

7) Automatic Versioning and Time StampingBy database versioning one can be assured that the changes done by one person is not being rollbacked by another one unintentionally. Hibernate enables developer to define version type field toapplication, due to this defined field Hibernate updates version field of database table every timerelational tuple is updated in form of Java class object to that table. So if two users retrieve sametuple and then modify it and one user save this modified tuple to database, version is automaticallyupdated for this tuple by Hibernate. When other user tries to save updated tuple to database then itdoes not allow to save it because this user does not has updated data. In JDBC there is no checkthat always every user has updated data. This check has to be added by the developer.

8) Open-Source, Zero-Cost Product LicenseHibernate is an open source and free to use for both development and production deployments.

9) Enterprise-Class Reliability and ScalabilityHibernate scales well in any environment, no matter if use it in-house Intranet that serves hundredsof users or for mission-critical applications that serve hundreds of thousands. JDBC can not bescaled easily.Hibernate Made Easy: Simplified Data Persistence with Hibernate and JPA (Java Persistence API) Annotations

Disadvantages of Hibernate

1) Steep learning curve.

2) Use of Hibernate is an overhead for the applications which are :• simple and use one database that never change• need to put data to database tables, no further SQL queries• there are no objects which are mapped to two different tablesHibernate increases extra layers and complexity. So for these types of applications JDBC is thebest choice.

3) Support for Hibernate on Internet is not sufficient.

4) Anybody wanting to maintain application using Hibernate will need to know Hibernate.

5) For complex data, mapping from Object-to-tables and vise versa reduces performance andincreases time of conversion.

6) Hibernate does not allow some type of queries which are supported by JDBC. For example It doesnot allow to insert multiple objects (persistent data) to same table using single query. Developerhas to write separate query to insert each object.

Jul 29, 2009

How DB locking system works in Hibernate (In Concurrency operations)

Database locking can apply to any database applications.
There are two common strategies when dealing with updates to database
records, pessimistic locking and optimistic locking.
"Optimistic locking" is more scalable than pessimistic locking when dealing with a
highly concurrent environment. However pessimistic locking is a better solution for situations
where the possibility of simultaneous updates to the same data by multiple sources
(for example, different applications use same database to update) is common, hence making the possibility of "data clobbering" , a
likely scenario. Lets look at a brief explanation of each of these two locking strategies.
Pessimistic locking is when you want to reserve a record for exclusive update by
locking the database record(entire table). Hibernate supports pessimistic locking
(using the underlying database, not in-memory) via one of the following methods:

1. Session.get
2. Session.load
3. Session.lock
4. Session.refresh
5. Query.setLockMode

Although each of the methods accepts different params, the one common parameter
across all is the LockMode class, which provides various locking modes such as NONE,
READ, UPGRADE, UPGRADE_NOWAIT, and WRITE.
For example, to obtain a Timesheet record for updating,
we could use the following code: (assume database supports locking system):

public Timesheet getTimesheetWithLock(int timesheetId)
{
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
Timesheet timesheet = (Timesheet)session.get(Timesheet.class,
new Integer(timesheetId), LockMode.UPGRADE);
session.getTransaction().commit();
session.close();
return timesheet;
}
Optimistic locking means that you will not lock a given database record or table and
instead check a property of some sort (for example, a timestamp column) to
ensure the data has not changed since you read it. Hibernate supports this using a
version property, which can either be checked manually by the application or automatically
by Hibernate for a given session. For example, the following code excerpt is taken
verbatim out of the Hibernate reference documentation and shows how an application
can manually compare the oldVersion with the current version using a getter method
(for example):

// foo is an instance loaded by a previous Session
session = factory.openSession();
int oldVersion = foo.getVersion();
session.load( foo, foo.getKey() );

if ( oldVersion!=foo.getVersion )
throw new StaleObjectStateException();


foo.setProperty(“bar”);

session.flush();
session.connection().commit();
session.close();

StaleObjectStateException, is an exception in the org.hibernate package.

Jul 27, 2009

Velocity example with FOR LOOP and Date format

/*Velocity example with Lists, date formate with htmls*/
import java.io.StringWriter;
import java.io.Writer;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.tools.generic.DateTool;

public class VelocityExp {

public static void main(String[] args) throws Exception {
Velocity.init();
Template t = Velocity.getTemplate("./src/test/VelocityExp.html");

VelocityContext ctx = new VelocityContext();
Set names =new HashSet();
Demov d1 = new Demov();
d1.setName("one");
d1.setAge("24");
d1.setKe(new demo2("one"));
Demov d2 = new Demov();
d2.setName("two");
d2.setAge("23");
d2.setKe(new demo2("two"));
Demov d3 = new Demov();
d3.setName("true");
d3.setAge("22");
d3.setKe(new demo2("three"));
Demov d4 = new Demov();
d4.setName("ofour");
d4.setAge("21");
d4.setKe(new demo2("four"));

names.add(d1);
names.add(d2);
names.add(d3);
names.add(d4);
ctx.put("products",names);
ctx.put("date", new DateTool());
ctx.put("dbdate",new Date());
ctx.put("rowCount",new Integer(1));
Writer writer = new StringWriter();
t.merge(ctx, writer);
System.out.println(writer);
}
}


Html file content:
<html>
<head>
<title>velocity test</title>
</head>
<body>
<table>
#foreach($product in $products)
#if ($rowCount % 2 == 0)
#set ($bgcolor = "#0000FF")
Applying BLUE color here
#else
Applying RED color here
#set ($bgcolor = "#FF0000")
#end
<tr>
<td bgcolor="$bgcolor">$product.name</td>
<td bgcolor="$bgcolor">$product.age</td>
<td bgcolor="$bgcolor">$product.ke.k</td>
</tr>
#set ($rowCount = $rowCount + 1)
#end
</table>
Displaying how to use date format here:
$dbdate
$date.get('medium')
$date.format('medium',$dbdate)
</body>
</html>

Jul 25, 2009

Java class with regExp

package com;

public class Name {
public static void main(String[] args) {
System.out.println(Name.class.getName().replaceAll(".", "/") + ".class");
}
}
Output:
////////.class

actually everyone thinks the output will be com/Name.class
In the case of replace '.' will treat as regExp, in regExp '.' means any type of character, here replacing with '/' , and it becomes output like "////////.class "

so, for expected answer, change the code as follows,

Name.class.getName().replaceAll("\\.", "/") + ".class");

then the output will, what you exprected,
Output:
com/Name.class

Jul 21, 2009

Small Answer for Small java pzzule!

/* What declaration turns this loop into infinitive loop.*/

public class GhostOfLooper {

public static void main(String[] args) {

// Place your declaration for i here

while (i != 0)

i >>>= 1;

}

}

Solution:

// Place your declaration for i here

byte i = -1;

Solution for java puzzles(3)

/*What declaration turns this loop into infinitive loop.*/

public class Looper {
public static void main(String[] args) {
// Place your declaration for i here

while (i == i + 1) {
}
}
}

Solution:
// Place your declaration for i here
double i = 1.0/0.0

Solution for java puzzles(2)!

/*Provide declarations for the variables x and i such that*/

public class Tweedledum {
public static void main(String[] args) {
// Put your declarations for x and i here
x += i; // Must be LEGAL
x = x + i; // Must be ILLEGAL
}
}
solution:
// Put your declarations for x and i here
int x=0;
byte i;

Solution for Java puzzles(1).

/*Provide a declaration for Enigma that makes the program print false.*/

public class TestClass{
public static void main(String[] args) {
Enigma e = new Enigma();
System.out.println(e.equals(e));
}
}

final class Enigma {
// Provide body that makes TestClass print false.
// Do n't override equals method in object class.
}
:Solution
final class Enigma {
public Enigma(){
System.out.print("false");
System.exit(0);
}
}
Any other solution will be appreciated ...

Jul 18, 2009

How to read Excel file in Java with jxl.jar?

/*Reading Excel file (with default locale) with jxl.jar file ,you can use file object to read file in workbook settings*/
public void processExcelFile(InputStream fileInput)throws Exception {
WorkbookSettings ws = new WorkbookSettings();
ws.setLocale(new Locale("en", "EN"));
Workbook workbook = Workbook.getWorkbook(fileInput, ws);
//Workbook workbook = Workbook.getWorkbook(file, ws);
//Cell[] headCells = sheet.getRow(0);
for (row = 1; row < sheet.getRows(); row++) {
String errorStr = "";
Cell[] cells = sheet.getRow(row);
System.out.println("column1 value:"+cells[0].getContents());
System.out.println("column2 value:"+cells[1].getContents());
System.out.println("column3 value:"+cells[2].getContents());
}
}
To download jxl.jar file go through this link
http://www.docjar.com/jar/jxl-2.6.jar