Friday, November 12, 2010

How to start working with Hibernate

Introduction of Hibernate

Detailed introduction can be found in various good books and tutorials however I am just giving the basic idea about hibernate.

Hibernate is a solution for object relational mapping and a persistence management solution or persistent layer. In other words : Lets assume you have an application with some features containing some business logic and you need to save data in the database. All the business logic resides in Java code which works with Objects, where your database (mysql, postgresql etc...) are not all deal with objects. Hibernate provides a solution to map database tables to a class.


There are few steps to start working with hibernate

1) Basic setup for hibernate
2) Create Database / tables
3) Create POJO for tables
4) Mapping POJO with DB table
5) Hibernate configuration
6) Log4j configs
7) Run the example


Basic setup for Hibernate

a) Install jdk1.5.x/1.6.x, JAVA_HOME and PATH must be set correctly.
b) download and extract zip/tar file of Eclipse IDE (I used Galileo).
c) download the following jars* from http://hibernate.org
ant-1.6.2.jar
ant-antlr-1.6.2.jar
ant-junit-1.6.2.jar
ant-launcher-1.6.2.jar
antlr-2.7.4.jar
ant-swing-1.6.2.jar
asm-3.3.jar
c3p0-0.8.5.jar
cglib-2.2.jar
cleanimports.jar
commons-collections-2.1.1.jar
commons-logging-1.0.4.jar
concurrent-1.3.2.jar
connector.jar
dom4j-1.5.2.jar
ehcache-1.1.jar
ejb3-persistence-3.3.2.Beta1.jar
hibernate-3.2.6.ga.jar
hibernate3.jar
hibernate-annotations-3.4.0.GA.jar
hibernate-commons-annotations-3.1.0.GA.jar
hibernate-core-3.3.0.SP1.jar
hibernate-entitymanager-3.4.0.GA.jar
hibernate-search-3.0.1.GA.jar
hibernate-validator-3.0.0.ga.jar
jaas.jar
jacc-1_0-fr.jar
jaxen-1.1-beta-4.jar
jboss-cache.jar
jboss-common.jar
jboss-jmx.jar
jboss-remoting.jar
jboss-system.jar
jdbc2_0-stdext.jar
jgroups-2.2.7.jar
jta.jar
junit-3.8.1.jar
log4j-1.2.9.jar
mysql-connector-java-3.0.16-ga-bin.jar
mysql-connector-java-3.1.6-bin.jar
oscache-2.1.jar
postgresql-8.2-504.jdbc3.jar
proxool-0.8.3.jar
swarmcache-1.0rc2.jar
versioncheck.jar
xerces-2.6.2.jar
xml-apis.jar

*some are not required e.g. if you are using mysql as your database then postgresql-8.2-504.jdbc3.jar is not required.

Create DB table (Postgres SQL) :

|--------------------------------------------------------------------|

CREATE TABLE "public"."emp" (
id SERIAL,
name text,
dob date
PRIMARY KEY(id)
);
|--------------------------------------------------------------------|

Create POJO Employee

package net.vs.example;

public class Employee {

private Integer id;

private String name;

private Date dob;

public Employee(){

}

public Integer getId() {

return id;

}

public void setId(Integer id) {

this.id = id;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public Date Dob() {

return dob;

}

public void Dob(Date dob) {

this.date = date;

}


Mapping POJO with DB table

You can use XML or annotations to define, how to map your class attributes to a database table.
Create the Employee.hbm.xml in the package net.vs.example and change it to the following

PostgreSQL Version:

xml version="1.0" encoding="UTF-8"?>

DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD

3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >

<hibernate-mapping>

<class name=net.vs.example.Employee table=emp>

<id name="id" column="id">

<generator class="sequence">

<param name="sequence"> emp_id_seq param>

generator>

id>

<property name="name" column = "name"/>

<property name="dob" column="dob" />

class>

hibernate-mapping>



Hibernate configuration

Create a file named “hibernate.cfg.xml” in your root directory
Insert the following in your hibernate file.


PostgreSQL Version:

xml version='1.0' encoding='UTF-8'?>

DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"

"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

<session-factory>

<property name="connection.url">

jdbc:postgresql://localhost:5432/myDB

property>

<property name="connection.username"> myuser property>

<property name="connection.driver_class">org.postgresql.Driverproperty>

<property name="dialect">org.hibernate.dialect.PostgreSQLDialectproperty>

<property name="connection.password">mypwdproperty>


<property name="hibernate.show_sql">trueproperty>

<mapping resource="employee.hbm.xmll" />

session-factory>

hibernate-configuration>


Configuring Log4J

As you can see above we added the log4j library. This library does like a configuration file in thesource directory or it welcomes you with the following error.

log4j:WARN No appenders could be found for logger (TestClient).

log4j:WARN Please initialize the log4j system properly.


Create a file named log4j.properties in the root directory and insert the following:

### direct log messages to stdout ###

log4j.appender.stdout=org.apache.log4j.ConsoleAppender

log4j.appender.stdout.Target=System.out

log4j.appender.stdout.layout=org.apache.log4j.PatternLayout

log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

### set log levels - for more verbose logging change 'info' to 'debug' ###

log4j.rootLogger=debug, stdout

log4j.logger.org.hibernate=info

#log4j.logger.org.hibernate=debug

### log HQL query parser activity

#log4j.logger.org.hibernate.hql.ast.AST=debug

### log just the SQL

log4j.logger.org.hibernate.SQL=debug

### log JDBC bind parameters ###

log4j.logger.org.hibernate.type=info

### log schema export/update ###

log4j.logger.org.hibernate.tool.hbm2ddl=info

### log HQL parse trees

#log4j.logger.org.hibernate.hql=debug

### log cache activity ###

log4j.logger.org.hibernate.cache=info

### log transaction activity

#log4j.logger.org.hibernate.transaction=debug

### log JDBC resource acquisition

#log4j.logger.org.hibernate.jdbc=debug

### enable the following line if you want to track down connection ###

### leakages when using DriverManagerConnectionProvider ###

#log4j.logger.org.hibernate.connection.DriverManagerConnectionProvider=trace



Run the example


TestHibernate.java

public class TestHibernate{

public static void main(String agrs[]) {

Session session = null;
try {

SessionFactory factory = new Configuration().configure().buildSessionFactory();
session = factory.openSession();

Employee emp = new Employee();
emp.setName("John");
emp.setDob(new Date());

session.save(emp);

} catch(Exception be){
be.printStackTrace();
}
finally {
// Actual contact insertion will happen at this step
if (null!=session){
session.flush();
session.close();
}

}

}


Cheers !




Wednesday, August 4, 2010

Life Cycle of a Bean in Spring


Life Cycle of a Bean in Spring

A Spring Bean is managed by IoC Container / Spring Container, whenever a bean is declared in the Spring configuration file, container will find it and do the following steps to make available for the application.

1) Firstly, spring creates an instance of the Bean using Java Reflection API.
2) If there are any properties associated with bean then spring injects those properties. If there are any bean as a peoperty then spring finds that bean and inject it.
3) If the Bean class implements the BeanNameAware interface, then the spring will call setBeanName() method by passing the name of the Bean.
4) If the Bean class implements the BeanFactoryAware interface, then the spring will call setBeanFactory() method by passing an instance of BeanFactory object.
5) If there are any BeanPostProcessors associated with the BeanFactory that loads the Bean, then the spring will call postProcessBeforeInitialization() method before the properties for the Bean are injected.
6) If the Bean class implements the InitializingBean interface, then the spring will call afterPropertiesSet() method once all the Bean properties defined in the Configuration file are injected.
7) If there is any custom init-method declared in the configuration file, that method will be called.
8) If there are any BeanPostProcessors associated with the BeanFactory that loads the Bean, then the spring will call postProcessAfterInitialization() method.
9) Now bean is ready to use.
10) If the Bean class implements the DisposableBean interface, then the spring calls destroy() method when the Application no longer needs the bean reference.
11) If there is any custom destroy-method declared in the configuration file, that method will be called.

Friday, June 25, 2010

Difference between ResultSet TYPE_SCROLL_SENSITIVE and TYPE_SCROLL_INSENSITIVE

Difference between ResultSet TYPE_SCROLL_SENSITIVE and TYPE_SCROLL_INSENSITIVE

If you would like to have a scrollable ResultSet Object then you need to supply constant when you create an object of it. By default it is FORWARD_ONLY, you can traverse forward in order to fetch records from table.

e.g. Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE , ResultSet.CONCUR_READ_ONLY);
Or
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE , ResultSet.CONCUR_READ_ONLY);

Or
Statement stmt = this.con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);

Or
Statement stmt = this.con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);


A result set that is TYPE_SCROLL_INSENSITIVE does not reflect changes made while it is still open and one that is TYPE_SCROLL_SENSITIVE does.
Changes will be visible if result set is closed and re-opened.

TYPE_SCROLL_SENSTIVE does not *guarantee* that all changes made to the result set by others will be visible.It depends on a number of factors including the driver implementation (whether it caches the rows or not), the transaction isolation level etc...

Wednesday, June 2, 2010

Why should use Stored Procedures

In software development its very common to interact with Database(s) and Application Layer used to fetch data from DB using any programming language like java, C# conjunction with SQL.
There are two kind of DB languages
1) SQL : Non procedural language, where you can not write your own logic / subroutines.
2) PL/SQL: Procedural language, where you can write business logic and subroutines.

Stored procedures used where we would require the following
* modular programming at DB level
* Faster execution.
* Reduce network traffic.
* Security mechanism.

Advantages:

->You can modify stored procedures independently of the program source code.The application doesn't have to be recompiled when/if the SQL is altered.
->Stored procedures abstract or separate server-side functions from the client-side.
->Stored procedures allow a lot more flexibility offering capabilities such as conditional logic.
->Stored procedures are stored within the databse and run directly in database engine, bandwidth and execution time are reduced. This is because a single stored procedure can execute a complex set of SQL statements.

Disadvantages:

->If we need to modify anything in stored procedure then its definition has to be replaced.
->Any changes in the stored procedure will impact all the places whereever this procedure is used.

How to create :
http://download.oracle.com/docs/html/B16022_01/ch3.htm
Examples in java:
http://www.oracle.com/technology/sample_code/tech/java/jsp/oracle9ijsp.html

Sunday, May 23, 2010

Best Strategy ? Abstract classess Or Interface

Few points before to proceed :

1) Abstract class can have one or more abstract methods as well as concrete methods.
2) An abstract class can't not be instantiated.
3) To use functionality of abstract class One can create a concrete class that has to instantiate the abstract class and must have implementation for each abstract method.
4) Abstract classes are usually declared where two or more subclasses are expected to fulfill a similar role in different ways through different implementations.
5) Interfaces defines the behavior of the classes. in another word Contract.
6) All methods declared in interface are abstract by default, no need to use abstract keyword.
7) Basic feature of OO is Encapsulation : Reveal an object's programming interface (functionality of the object) without revealing its implementation.
8) Interfaces have no direct inherited relationship with any particular class, they are defined independently. Interfaces themselves have inheritance relationship
among themselves.

When Should Interfaces or Abstract classes some point are below :
First and very important is "Choice of design".
Second there are some facts and features of each, according to design we should use them.

1) Using Interfaces, The implementation can change without affecting
the caller of the interface.
2) Using Interfaces, Unrelated (One class is not a sub-class of another class) classes can implement similar methods(behaviors).
3) An interface can only define constants while abstract class can have fields.
4) Use Abstract classes, where you want to provide common implementation code for all its sub classes. It reduces the duplication. However we should not forget that a concrete can extend only one super class whether that super class is in the form of concrete class or abstract class.

I would use interfaces when I think that something there are very frequent changes in my design. How??? Simple example :

Consider an interface that you have developed called "TaskHandler":

public interface TaskHandler{
void performSomething(int i, float x);
int performMore(String s);
}


Now after some time , you want to add a third method to "TaskHandler", so that the interface now becomes:

public interface TaskHandler{
void performSomething(int i, float x);
int performMore(String s);
boolean willYouPerform(int i, float x, String s);
}


Points to be noted:

If you make this change, all classes that implement the old TaskHandler
interface will break because they don't implement all methods of
the the interface now.

Solution :
Create one more interface OtherTaskHandler that extends TaskHandler interface

public interface OtherTaskHandler extends TaskHandler {
boolean willYouPerform(int i, float x, String s);
}


Now Its up to users, he/she can choose to continue to use the old interface or to upgrade to the new interface.

Tuesday, May 18, 2010

Java is not a Pure Object Oriented Language






Theoretical a Pure Object Oriented Language must contains all entities as in the form of Object. There could be two categories of OOPL :
1) Hybrid OO languages :
Hybrid languages are based on some non-OO model that has been enhanced with OO concepts. e.g. C++, ancestor was C, may be more...

2) Pure OO languages
Pure OO languages are based entirely on OO principles; Smalltalk, Java, and Simula are pure OO languages.

But Due to following reasons Java can't be considered as Pure OOPL:
1) Java violates principle "Everything must be Object". Java has primitive types int, long etc.
2) static works on class level.
3) Multiple inheritance is not supported.
4) Operator overloading is not supported.

BTW Java never claimed to be "Pure OOPL".

Sunday, March 28, 2010

Refactoring of Code

Refactoring is basically a continuous job for a software programmer to improve code quality and maintainability.
Some good software programmer used to do this with / without knowing of it e.g. moving methods to the super class / abstract class, making general function to do more stuff in small code etc. Generally there will not be extra time given for refactoring the code, unless the code is not able to use without doing it. Whenever a new feature or bug arrives refactoring should be done to improve quality,maintainability and extendability of code.

Software developers are often not willing to do refactoring, because some refactoring are simply tedious and also there is no visible external benefit for all the efforts put in.

It is very common that management only emphasis / rewards externally visible code like new feature and enhanced performance etc but very much not interested to code's quality. However after the code reviews if software developers want to spend some time to refactoring the code, there could be some risk of breaking code via refactoring operations e.g. code is not written as per the coding standards etc.

A software developer wants to refactor some poorly written / structured code, their lead or manager would have a different vision altogether on it and its very common that he /she may deny to modify the working / deployed code. These things also can't be ignored. Sometimes developer and management take decision together of refactoring of bad code.