Thursday, February 26, 2009

What Is Hibernate

Hibernate
Hibernate is a free, open source Java package that makes it easy to work with relational databases. Hibernate makes it seem as if your database contains plain Java objects like you use every day, without having to worry about how to get them out of (or back into) mysterious database tables. It liberates you to focus on the objects and features of your application, without having to worry about how to store them or find them later.
This article discusses the following:
History and Background
How Hibernate Works
When to Use Hibernate
Learning More
History and Background
Most applications have some need to work with data. Java applications, when running, tend to encapsulate data as networks of interconnected objects, but those objects vanish in a puff of logic when the program ends, so there needs to be some way to store them. And sometimes the data is already "out there" before the application is even written, so there needs to be a way to read it in and represent it as objects. Writing code by hand to perform these tasks is tedious and error-prone, and can represent a major portion of the effort involved in the overall application.

As good object-oriented developers got tired of this repetitive work, their typical tendency towards enlightened laziness started to manifest itself in the creation of tools to help automate the process. When working with relational databases, the culmination of such efforts were object/relational mapping tools.

There have been a variety of such tools, ranging from expensive commercial offerings to the EJB standards built into J2EE. In many cases, however, the tools introduce their own complexity, force the developer to learn detailed rules for using them, and to modify the classes making up their applications to conform to the needs of the mapping system. As the tools evolved to handle ever more rigorous and complex enterprise requirements, the intricacies required to use them started to overwhelm the savings you could obtain by doing so in simpler, common cases. This has led to something of a revolution favoring more lightweight solutions, of which Hibernate is an example.

How Hibernate Works
Hibernate doesn't get in your way; nor does it force you to change the way your objects behave. They don't need to implement any magical interfaces in order to be blessed with the ability to persist. All you need to do is create an XML "mapping document" telling Hibernate the classes you want to be able to store in a database, and how they relate to the tables and columns in that database, and then you can ask it to fetch data as objects, or store objects as data for you. Compared to most of the alternatives, it's almost magical.

There isn't room in an introductory article like this to work through a concrete example of building and using a Hibernate mapping document (that's what the first couple of chapters in my Hibernate: A Developer's Notebook are for, after all). And there are some good examples already on the Web and in the Hibernate online documentation; see "Learning More," on page 2. It really is straightforward, though. Properties in the application objects are associated with appropriate database structures in a simple, natural way.

At runtime, Hibernate reads the mapping document and dynamically builds Java classes to manage the translation between the database and Java worlds. There is a simple, intuitive API in Hibernate to perform queries against the objects represented by the database. To change those objects you just interact with them normally in the program, and then tell Hibernate to save the changes. Creating new objects is similarly simple; you just create them in the normal way and tell Hibernate about them so they can get stored to the database.

The Hibernate API is simple to learn and interacts quite naturally with the flow of your program. You invoke it in sensible places, and it does what you'd like it to. The benefits it brings in terms of automation and code savings greatly outweigh the short time it takes to learn. And you get an additional bonus in that your code doesn't care (or even have to know) what kind of database you're using. My company has had projects forced to change database vendors late in the development process. This can be a horrible mess, but with Hibernate it has required nothing more than a single change to the Hibernate configuration file.

This discussion has assumed that you already had a relational database set up, as well as Java classes to map, through the creation of the Hibernate mapping document. There is a Hibernate "toolset" that works at build time to support different workflows. For example, if you've got the Java classes and mapping document, Hibernate can create (or update) the necessary database tables for you. Or, starting with just the mapping document, Hibernate can generate the data classes for you, too. Or it can reverse engineer your database and classes to sketch out a mapping document for you. There are also some alpha plugins for Eclipse to provide intelligent editing support and graphical access to these tools right from within the IDE.

If you're in a Hibernate 2 environment, fewer of these tools are provided, but there are third-party options available.

What is JDBC?

JDBC is Java application programming interface that allows the Java programmers to access database management system from Java code. It was developed by JavaSoft, a subsidiary of Sun Microsystems.

Definition

Java Database Connectivity in short called as JDBC. It is a java API which enables the java programs to execute SQL statements. It is an application programming interface that defines how a java programmer can access the database in tabular format from Java code using a set of standard interfaces and classes written in the Java programming language.
JDBC has been developed under the Java Community Process that allows multiple implementations to exist and be used by the
same application. JDBC provides methods for querying and updating the data in Relational Database Management system such as SQL, Oracle etc.
The Java application programming interface provides a mechanism for dynamically loading the correct Java packages and drivers and registering them with the JDBC Driver Manager that is used as a connection factory for creating JDBC connections which supports creating and executing statements such as SQL INSERT, UPDATE and DELETE. Driver Manager is the backbone of the jdbc architecture.
Generally all Relational Database Management System supports SQL and we all know that Java is platform independent, so JDBC makes it possible to write a single database application that can run on different platforms and interact with different Database Management Systems.
Java Database Connectivity is similar to Open Database Connectivity (ODBC) which is used for accessing and managing database, but the difference is that JDBC is designed specifically for Java programs, whereas ODBC is not depended upon any language.
In short JDBC helps the programmers to write java applications that manage these three programming activities:

1. It helps us to connect to a data source, like a database.
2. It helps us in sending queries and updating statements to the database and
3. Retrieving and processing the results received from the database in terms of answering to your query.

Accessing EJB In JBoss From Swing Client

This articles shows how to access a simple stateless session bean in EJB 3.0 from a Swing client. Though it sounds like a simple process, it needs good number of steps. You need to use good number or .jar files and properties to access ejb 3.0 from a remote client.

At the end of this article you will have learnt how to do the following:

Creating a simple stateless session bean using JBoss and NetBeans.
Getting access to Naming Service of JBoss from remote client
Using appropriate .jar file of JBoss to access an EJB deployed in JBoss from a remote client.
Creating a simple stateless session bean in JBoss with NetBeans
Follow the steps and code given below to create a stateless session bean with a single method. I use JBoss as the EJB Container and NetBeans IDE.
First configure NetBeans to use JBoss as application server using Tools ->Server Manager option of NetBeans.
Create a new project using File->New Project
Select Enterprise as category and EJB Module as type of project
Enter HelloEJB as the name of the project
Select Stateless and type of EJB and Remote as the interface
NetBeans provides - HelloRemote.java and HelloBean.java
Go to HelloBean.java. Invoke popup menu (right click) and select EJB Methods->Add Business Method
Enter sayHello as name of the method and String as return type
Write the code shown below. At the end of the process HelloRemote.java and HelloBean.java should be as shown below.
// HelloRemote.java
package st;
import javax.ejb.Remote;

@Remote
public interface HelloRemote {
String sayHello();
}
// HelloBean.java
package st;
import javax.ejb.Stateless;

@Stateless
public class HelloBean implements HelloRemote {

public HelloBean() {
}

public String sayHello() {
return "Hello";
}
}
Go to Projects window using Window->Projects
Right click on project name to invoke popup menu and select Deploy Project option to deploy project
Creating Swing Client
Now, let us create a frame-based swing application to access EJB. This swing application runs on its own and not in JBoss. So, it is called as remote client to EJB. Client project needs to have access to a couple of .jar files to access to JBoss and EJB deployed in JBoss.

Take the following steps related to client:

Create a new project using File->New Project
Select General in category and Java Application as project type
Give project name as SwingClient
Select the project (SwingClient) in Projects window. Go to libraries node, right click and select Add Jar/Folder .
Add the following libraries (.jar files) to SwingClient project.
HelloEjb.jar - Jar file of HelloEJB application. This is found in dist directory of the project
jboss-ejb3-client.jar, jboss-aop-jdk50-client.jar, jboss-aspect-jdk50-client.jar and jbossall-client.jar - all these .jar files are found in client folder of JBoss installation directory( For ex, d:\jboss)
Add a Java class (HelloClient) to project using File->New File, select Java Classes in categories and Java Class as File Type
Write the following code in HelloClient.java
import java.util.Properties;
import javax.naming.InitialContext;
import javax.swing.JOptionPane;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import st.HelloRemote;

public class HelloClient extends JFrame {
public HelloClient() {
super("Hello Client");
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
JButton b1 = new JButton("Access EJB");

getContentPane().add(b1, BorderLayout.PAGE_END);

b1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
String msg = "";
try {
// Access JNDI Initial Context.
Properties p = new Properties();
p.put("java.naming.factory.initial","org.jnp.interfaces.NamingContextFactory");
p.put("java.naming.provider.url","jnp://localhost:1099");
p.put("java.naming.factory.url.pkgs","org.jboss.naming:org.jnp.interfaces");
InitialContext ctx = new InitialContext(p);
// Change jndi name according to your server and ejb
HelloRemote remote = (HelloRemote) ctx.lookup("HelloBean/remote");
msg = "Message From EJB --> " + remote.sayHello();
}
catch(Exception ex){
msg = "Error --> " + ex.getCause().toString();
}
JOptionPane.showMessageDialog(HelloClient.this,msg,"Message", JOptionPane.INFORMATION_MESSAGE);
}
});
setSize(200,200);
} //
public static void main(String args[]) {
new HelloClient().setVisible(true);
}
}
Run HelloClient class by selecting Run File option from popup menu (right click).
Click on Access EJB button and you must see a message dialog with message coming from ejb - Hello.
I hope this article helps you to understand how to access an EJB deployed in JBoss from a remote client. Remote client may be a swing application, a console application or a web application.

Web Service with AXIS

This article shows how to use AXIS from Apache to host Web Services using Tomcat5.

What is Web Service?

Web service is a collection of methods that can be accessed over internet using SOAP (Simple Object Access Protocol). SOAP itself is making use of HTTP and XML to encode and trasfer data.
Web services are interoperable , which means a Web service created in Java can be accessed from .NET and vice-versa.

What is AXIS?

AXIS is SOAP engine which works on server and client. It allows Java classes to be deployed as Web services so that they can be accessed from anywhere.
AXIS stands for Apache Extensible Interaction System. It is an open-source project and implements standard JAX-RPC API of Java.

How to install Axis?

Axis must be downloaded from axis.apache.org. It comes as a simple .zip file axis-bin-1_3.zip Extract this zip file to D drive will result in a folder with the name d:\axis-1_3.
Copy axis directory of d:\axis-1_3\webapps into webapps directory of Tomcat5.
Start Tomcat and test whether the Axis web application is running using http://localhost:8080/axis . Please change port number 8080 with port number that you use for Tomcat in your system.
Test whether Axis has access to all required libraries by using http://localhost:8080/axis/happyaxis.jsp. If any core libraries are missing, make sure you copy them to either WEB-INF/lib directory of Axis or common\lib directory of Tomcat.
Creating and comsuming a simple Web service
The following procedure explains how to create a invoke a simple web service, which has a single method sayHello().
Create the following class and place it in axis directory under the name Hello.jws.
public class Hello
{

public String sayHello( String name)
{
return "Hello," + name;
}
}
Test the web service by giving the url http://localhost:8080/axis/Hello.jws.
You must see the message saying that there is a web service installed. Click on wsdl hyperlink to see WSDL for the service.
Once service is deployed successfully then run the client by first setting the CLASSPATH and PATH as follows:
set AXIS_HOME=d:\axis-1_3
set AXIS_LIB=%AXIS_HOME%\lib
set AXISCLASSPATH=.;%AXIS_LIB%\axis.jar;%AXIS_LIB%\commons-discovery-0.2.jar;%AXIS_LIB%\commons-logging-1.0.4.jar;%AXIS_LIB%\jaxrpc.jar;%AXIS_LIB%\saaj.jar;%AXIS_LIB%\log4j-1.2.8.jar;%AXIS_LIB%\xml-apis.jar;%AXIS_LIB%\xercesImpl.jar

set classpaht=.;%classpath%;%AXISCLASSPATH%

path c:\jdk1.5.0\bin

You have to copy xercesimpl.jar and xml-apis.xml or something similar to it must be copied into lib directory of d:\axis-1_3.
HelloClient.java is the client program to access web serice.

import org.apache.axis.AxisFault;
import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.axis.encoding.XMLType;
import org.apache.axis.utils.Options;

import javax.xml.namespace.QName;
import javax.xml.rpc.ParameterMode;
import java.net.URL;

public class HelloClient
{
public static void main(String args[]) throws Exception
{

Service service = new Service();
Call call = (Call) service.createCall();
call.setTargetEndpointAddress( "http://localhost:8080/axis/Hello.jws");
call.setOperationName("sayHello");
Object ret = call.invoke( new Object[] {"Srikanth"} );
String res = (String) ret;
System.out.println(res);
}
}

Then complie and run the following client.
javac HelloClient.java
java HelloClient
You must see message saying Hello,Srikanth. If you get any warning regarding Log4j, ignore them.
Installing a Web service by just copying .jws file into axis directory is called as drop-in deployment.
Deploying Web Serice using Custom deployment
The following example demonstrates how to deploy a web serice using a .class of Java. We want to expose a few methods (or all) of a Java class as web methods in web service. This can be done by the following procedure:
Create Hello.java as follows:
public class Hello
{

public String sayHello( String name)
{
return "Hello," + name;
}
}
Compile Hello.java and copy Hello.class into WEB-INF/classes directory of axis application in Tomcat.
Create Hello.wsdd , which contains details of the sercice as follows:
xmlns:java="http://xml.apache.org/axis/wsdd/providers/java">






Run AdminClient to deploy service in Hello.wsdd as follows:
java org.apache.axis.client.AdminClient -lhttp://localhost:8080/axis/services/AdminService deploy.wsdd
Test web service by using http://localhost:8080/axis/services/hello. You must see a page saying this is a web service.
Create the HelloClient.java as follows:
import org.apache.axis.AxisFault;
import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.axis.encoding.XMLType;
import org.apache.axis.utils.Options;

import javax.xml.namespace.QName;
import javax.xml.rpc.ParameterMode;
import java.net.URL;

public class HelloClient
{
public static void main(String args[]) throws Exception
{
Service service = new Service();
Call call = (Call) service.createCall();
call.setTargetEndpointAddress( "http://localhost:8080/axis/services/hello");
call.setOperationName("sayHello");

Object ret = call.invoke( new Object[] {"Srikanth"} );
String res = (String) ret;
System.out.println(res);
}
}
Compile and run HelloClient to get call sayHello() method. The return value will be Hello,Srikanth .
Conclusion
Axis really made the process of creating and deploying web serice in Java very simple. All that you have to create a web service is Tomcat5.x and Axis and a Java compiler (J2SE 5.0).
For further information, refer to axis.apache.org. Also remember axis comes with full documenation in docs directory.
Click Currency Converter Example to see how to create a currency conveter web service and corresponding client.

Introduction To Struts

Introduction To Struts

Every now and then IT industry has come out with something new. It was Java in mid 90s and .NET in 2000 and so on. All these things changed the way programmers write programs.
Java changed the preception of programmer. It let programmers concentrate on application logic more than house-keeping issues like memory management and thread management.
.NET from Microsoft came in 2000 has provided a new platform for application development. We say we develop applications for .NET and not Windows.
J2EE is widely accepted by industry. Java has grown from strength to strength in both Web application development and enterprise application development. First came Servlets, then JSP, EJB and now Java Struts.

What is Java Struts?

If you are hearing this for first time then you are not alone. Not many know it as of now, but at the same time many use it.
Struts is used to develop web applications. It is a web application framework based on JSPs, Servlets and Java Beans.
Struts project was initiated in May,2000 by Craig R. McClanahan and in July,2001 Struts 1.0 was released.
In MVC (Model-view-Controller) design pattern, Controller acts as a mediator between View (presentation) and Model (data). Prior to Struts, MVC was implemented using JSPs. The entire development was JSP Centric. In Model 2 of MVC, we use Servlets and JSPs. JSPs take care of generating HTML (view) and Servlets take care of controlling the flow. Java Beans are used to contain model (data). Beans may take data from either a database or an EJB or any other conceivable source.
View - Presentation
View portion is handled in Struts using JSPs. Struts provide a set of custom tags, which internally generate HTML. The best part of it is these HTML pages can be very easily internationalized. It means the view portion can be in any language. It takes almost no time to shift an application from English to Spanish.
View portion handled by custom tags is intergarted with Model, which is represented by Java Bean.
Controller - controlling the flow
Controller portion is handled by Servlet. ActionServlet in Struts takes request and decides which action should take place. The Action component performs business logic and then transfer control to view portion for display.

What you need to use Struts?

The following are the component required to use Struts.
Jakarta Struts library.Download struts library 1.1 , which is 16 MB.
Tomcat 4.0 or highter
JDK 1.4 to compile Java Beans
Do the following after you install Jakarta Struts 1.1.
Unzip the .ZIP file into folder
Copy struts-documentaion.war from webapps directory of the folder into which you extracted ZIP file into webapps directory of Tomcat.
Start Tomcat server
Enter the url http://localhost:8080/struts-documentation. Struts documentation is provided as one of the sample web applications.
First application
I have developed a simple Struts application. Download first.zip and extract it into webapps directory of Tomcat. Then start tomcat and run the url http://localhost:8080/first to see the sample application in action.
Java struts provides a few sample applications to demonstrate Struts. However, my application (first) will give an overview of struts without overwhelming you.

Custom tags and JSPs interaction

Custom tags are not new to any JSP programmer. In this article, I would like to create a custom tag that demonstrates how a custom tag interacts with JSP using attributes.

In case you are new to custom tags in JSP 2.0, see article Creating and using custom tags.

I will create a custom tag called , which takes an SQL query and makes data retrieved by the query available to JSP through attributes.The following are the steps to be taken to develop this tag and use it.

The first step is to create the tag handler as follows:
package st;

import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import java.sql.*;


public class QueryHandler extends SimpleTagSupport {
private String sql;

public void doTag() throws JspException {
JspWriter out=getJspContext().getOut();
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","hr","hr");
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(sql);
JspContext ctx = getJspContext();

// get data related to ResultSet
ResultSetMetaData rsmd = rs.getMetaData();
int count = rsmd.getColumnCount();
JspFragment f=getJspBody();

while ( rs.next()) {
for(int i = 1 ; i <= count ; i ++ ) {
// Create an attribute for each column.
// Column name is attribute name and value is attribute's value.
ctx.setAttribute( rsmd.getColumnName(i), rs.getString(i));
}
// process the body of the tag and send result to JSPWriter
f.invoke(out);
}
rs.close();
con.close();
} catch (Exception ex) {
throw new JspException(ex.getMessage());
}
}
// attribute sql
public void setSql(java.lang.String value) {
this.sql = value;
}
}


In the above Tag Handler, we use SQL query passed through attribute sql to retrieve data. The data is placed in ResultSet. For each row of the ResultSet we create a set of attributes - one for each column. The name of the attribute is column name and value is column's value. To get names of columns we have to get ResultSetMetaData object from ResultSet.

NOTE : The column names are in uppercase. So even the attribute names are in uppercase. In case you want to create attributes with lowercase names, use toLowerCase() method of String class as follows:
ctx.setAttribute( rsmd.getColumnName(i).toLowerCase() , rs.getString(i));

The following is tab library descriptor (st.tld) for the above tag.


1.0
Srikanth Technologies Tags
/WEB-INF/tlds/st

query
st.QueryHandler
scriptless

sql
true
true
java.lang.String





Now, let us register st.tld in a JSP using taglib directive and use tag. The following JSP shows how to use it.
<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8"%>
<%@taglib uri="/WEB-INF/tlds/st.tld" prefix="st"%>


"http://www.w3.org/TR/html4/loose.dtd">




Using Query Tag


Query





  • ${DEPARTMENT_ID}, ${DEPARTMENT_NAME}









TitleMin Salary
${JOB_TITLE} ${MIN_SALARY}






First usage of query tag is to retreive details from DEPARTMENTS table. Attributes DEPARTMENT_ID and DEPARTMENT_NAME are created from tag handler. Those attributes are used in JSP using Expression Langauge (EL) syntax. By making data available using attributes, we allow JSP to display data in the way it wants. It is demonstrated by second usage of tag as we used a table to display the data of attributes.
This article shows how to make use of the following:
Creating a custom tag using JSP 2.0 simple tag technique
Getting Connection to Oracle . Make sure you make JDBC driver available to web application.
Using ResultSet and ResultSetMetaData to get information about ResultSet
Creating page attributes in custom tag to make data available to JSP in which tag is used
Using attributes created by custom tag with expression language
The concept of custom tags is very powerful. JSTL, JSF and even frameworks such as Struts make use of custom tags extensively. So, it is worth understanding how custom tags and JSPs interact.

Creating a Servlet without any IDE

In this article, I want to show how to create a simple servlet without using any IDE like NetBeans or Eclipse. I will use Tomcat 6.0 and Notepad to create a simple test servlet and run it.

The article assumes, you have JDK 5.0/6.0 and Tomcat 6.0.

The following are the steps to be taken by you to create a simple servlet.

Download Tomcat 6.0 from http://tomcat.apache.org
Install Tomcat 6.0 into c:\ApacheTomcat6.0
Go to webapps directory of Tomcat and create the following directory structure for demo application. Any directory placed with required structure of Java EE web application is treated as a web application by Tomcat.
demo
WEB-INF
classes
TestServlet.java
web.xml

Creating Servlet Source Code
The following is the code for TestServlet.java. It simply sends a message to browser.

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class TestServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();

}

public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
doGet(request, response);
}
}
Deployment Descriptor - web.xml
Create web.xml as follows. It is better you copy web.xml from some other application in Tomcat webapps directory instead of typing it from scratch. Make sure it is placed in WEB-INF (in uppercase) folder of demo application with the following content.

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">

TestServlet
TestServlet


TestServlet
/test




TestServlet is associated with url pattern /test in web.xml. From the client, we have to make request for url pattern /test.
Compiling Servlet
Go to classes directory, where .java file is placed as enter the following commands at the command prompt to compile the servlet.
path=d:\jdk1.6.0\bin
set classpath=.;c:\apachetomcat6.0\lib\servlet-api.jar
javac TestServlet.java

Make sure you change JDK and Tomcat directories according to your installation.

Set path to the directory where JDK is installed. Servlet-api.jar contains API related to servlet like HttpServlet, HttpServletRequest etc., so it must be placed in the classpath. Compile the servlet (.java) to create .class file.

Starting Tomcat and Running Servlet
Start Tomcat by taking the follwing steps from BIN directory of Tomcat.
set java_home=d:\jdk1.6.0
startup

Once, tomcat is successfully started, go to browser and enterer the following URL.
http://localhost:8080/demo/test
You must see the output as follows.