Pradeep's Blog

Google

Monday, March 27, 2006

How to use Hibernate

As mentioned in my earlier blog hibernate is used to persist data stored in the objects into a data base. For this to happen there are three things that are needed. One a java data classes (whose object’s properties we want to persist).Two an xml file mapping this class to the respective table, and also the properties of the class into appropriate classes. This file tells Hibernate how & which data to store. The third thing that we need is an xml file that configures Hibernate. The purpose of this file is to tell Hibernate what database it has to use, mapping file information, and other defaults.

Once these three are ready, we can use another class to populate the data, then hibernate can be used to in synchronise the object’s properties into their mapped columns in the database.

Sunday, March 26, 2006

Need for an ORM package like Hibernate?

Relational database management systems are proven data management technology and are almost always a requirement in any Java project. While using objects in our application, we sometimes reach the point where we want them to persist using a RDBMS. We would typically open a JDBC connection, create an SQL statement and copy all our objects property values over.

Since Java does not have SQL type, we are forced to use String concatenation which errors prone and time consuming. This may be easy for objects with small set of properties, but for an object with many properties just preparing the SQL statement would itself be complicated.

That’s not the only problem, what about things like associations, foreign key constraints? And situations like adding a new property to an object half way through the development, trying to use the application with other database; do we go and change all associated SQL statements in the code to suit our new needs? Remember that the problem applies to both loading properties from the database into object’s properties and Vis-versa.

So what can Hibernate do for us? Hibernate basically intends to takes most of that burden of our shoulder. By using Hibernate we only have to define the way we map our classes to tables once - which property maps to which column, which class to which table, etc. After this, we should be able to do things like this:

session.save(MyObj);//statement 1
myObject = session.load(MyObject.class, objectId);//statement 2


The first statement saves the objects properties into the appropriate column in the database table & the second statement the opposite as per our mapping.

Hibernate will automatically generate all the SQL needed to store the object. It relieves us of manual JDBC result set handling, objects conversion, and keeps our application portable to all SQL databases, leaving us to concentrate on the business logic alone. Hence Hibernate helps in rapid product development, minimises maintenance & development costs.
References:

Monday, March 20, 2006

Good Ways of Handling Exception in Java

Not that I know everything in exception handling, but here's what i think are good ways of handling exceptions.
  • Never use a catch block that suppresses the exception (for example by doing nothing). This makes the program to continue on as if nothing ever happened.
  • Always try to catch the specific exception, unless you are sure that it makes no difference. For example when invoking a method that throws more that one type of exception, never just catch them using Exception.
  • Handle exceptions where actions can be taken to deal with the exceptions caused. For example if a block of code throws an exception, handle it there only ifs possible for you to recover from the exception, or else throw the exception to a level where the system can recover.
  • Having said to throw the exceptions to an upper level where it can be comfortably handled, it dosent mean that you throw an fileNotFound Exception to a place where the applications logical level.
  • When deciding on checked or unchecked exceptions exceptions for your APIs, its good to throw an checked exception if its possible for the client to recover from the exception, or else it can be should unchecked exception.
  • Allways clean up afer exception using finally.

How to integrate Junit into Ant?

Ant provides a flexible JUnit task for compling and executing JUnit tests. I hope that you all know what how test classes are written in java. Consider that we have a class named metricEngine and a class named metricEngineTest to test it.
The first thing that has to be done is that both the classes needs to be compiled. This can be done in Ant as follows (considering that both the files are in basedir itself).


<target description="Compiling Files." depends="init" name="compile.source">
<echo>Compiling Files
<javac destdir="${destdir}" srcdir="${basedir}" target="1.5" source="1.5">
<classpath refid="classpath">
<include name="**">
</javac>
</target>


The classpath includes the list of libary files needed to compile these files. They can be set as follows (consider that the basedir/lib contains all the required library (jar) files.


<path id="classpath">
<fileset dir="${basedir}/lib">
<include name="*.jar">
</fileset>
</path>


Now that both the files have been compiled we can test them, this can be done as follows


<target description="Runs the test suite" depends="compile.test" name="test">
<printsummary="yes" fork="yes" haltonfailure="no" showoutput="yes">
<formatter type="plain" usefile="false">
<classpath refid="classpath">
<lt todir="${basedir}/test-result.txt" fork="yes">
<fileset dir="${destdir}">
<include name="**/metricEngineTest.class">
</fileset>
</batchtest>
</junit>
</target>


MOre information on the JUnit tag can be found with ANT Documentation.

Thursday, March 16, 2006

Data Recovery, My Experience !

My portable hard disk crashed (my computer was able to recognise it but not able to open it) today. I guess some important file that deals with the file format & things like that got corrupted. There was a lot of data in the disk (some were not important & others I had backup). But I did not have a back up for a collection of e-books (around 6GB).

I used software called recovermyfiles. It was pretty good, once I checked the files that I wanted it to recover it started recovering files. But just to scan 1 percent of the disk it took about 15 minutes & the files that were recovered were all named as recovered filesomenumber.extension. I seemed that too much time would have been needed to just sort the recovered data.

So, after just fifteen minutes of my hard disk crashing I am reformatting it (about 80% over now). And what about the ebook collection, well definitely I was not going to read all of them & I know how to get the books that I may need. Good thing it happened, i now dont have so much unwanted stuff...

Tuesday, March 14, 2006

How to use Xstream to serialise and de-serialise

In order to use xstream you require xstream-[version].jar and xpp3-[version].jar in the classpath. These files can be downloaded from xstream.codehaus.org. The xpp3-[version] is an alternative to the JAXP DOM parser.
Once these files have been placed in your classpath, you are ready to use xstream.Consider a simple java class having only set methods for variables that it has.
Project.java
class project {
private String projectName;
private ArrayList classFiles = new ArrayList();
private ArrayList jarFiles = new ArrayList();
}

Xml File that has to be serialized into project.java:

<>
< projectName> test/projectName>
&ltfile>cyvis.java
<file>test2
&lt/classFiles>

<file>file1
test2
&lt/jarFiles>


Code to serialise:

String xml = readFile(xmlFileName);
//reads contents of the xml into a string.

XStream xstream = new XStream();
//to use xstream you need a instance of it.

xstream.alias("project", Project.class);
xstream.alias("file", String.class);

//setting alias is optional, but doing so your can have tags that are meaningful
//for example instead of project.class you can have project.

project = (Project) xstream.fromXML(xml);
//fills in the Project
Now something like project.getName() will return you the name that was given in the project.

Tuesday, March 07, 2006

How to Use HSQLDB with JSP

I presume that you already have a server like Tomcat installed and therefore will just concentrate on how to install HSQLDB in order to use it with JSP.

HSQLDB can be downloaded from
here. After downloading extract the zip file & find a jar file named hsqldb.jar.. Copy this file into commons/lib of your web server installation . Once this is done, HSQLDB is ready for use with JSP/ Servlets.

A new database is created automatically if it does not yet exist. Just connect to the not-yet-existing database using the jdbc:hsqldb:file:«database-path» URL (should replace the last part with the path you want) with the user 'sa' and an empty password. For more on HSQLDb please visit this page.

Monday, March 06, 2006

Which Codec Should I Use?

A codec is software that is used to compress or decompress a digital media file, such as a song or video. Windows Media Player, Windows Movie Maker, and other programs use codecs to play and create digital media files.
In the past few years their have been many new codec's developed, so it’s not possible for these programs to come with all the new codecs. When your operating system or the program does not support the codec that was used to compress the file, you can either download the codec separately (if you know which one is missing) or install the new codecs that are bundled together. Some of the places to find codecs bundled are:

Though the first option looks easier I recommend you finding the exact codec that is needed and install it. Programs like Gspot Codec Tool let you know which codec you may require to run a particular file.