Thursday 25 September 2008

Hibernate short summary part-I

Hibernate addresses the one of the most important aspects of the Java applications, the data persistence. The data persistence facilities in the form of objects make it one of the most successful frameworks. I.e. as a Java programmer you see the underlying database tables as objects. Storing a row in the table for you is saving an object instance. The relation between the 2 tables for you is the references between the 2 objects, very simple indeed :). Guys believe me...if you are able to get these lines ...you have done the very first homework of learning the hibernate ... This is not a rocket science... have fun :)

This characteristic of hibernate is called the ORM [Object relational mapping] ORM is a piece of software/product for the representation and conversion of data between the database and the object-oriented programming language.

Another important feature which interests me most is that you need not worry about the database specific queries. e.g. the sql query to do some task X in oracle may be different from SQL Server, as a hibernate user I would not bother about it ... hibernate takes care of this for me .. how? We would come to it at appropriate time.

Things don't interest programmers unless they get their hands dirty with the codes and I would try to make things work for you in most simple way.

What you need to do next then?
1. Download and latest Hibernate. Hibernate is available for download at http://www.hibernate.org/
2. Create a simple java project in eclipse and Include the hibernate.jar file in the working directory. [don't know eclipse .. have coffee ..watch and learn here ]
3. Its good that you have some database installed.
4. Place your JDBC driver jar file for relevant to your database in the java project classpath.
5. You must know the connection parameters for your database. This could be the most frustrating thing for you to be able to run your hibernate application first time. Please note down your database connection URL, database name, port number, username, passwords etc. for more details read this

Next step is to create a simple USER table in the database as following ..

USER_ID <PK> int(10)
USER_NAME varchar(20)
USER_ PASSWORD varchar(10)
USER_ EMAIL varchar(20)

As I already said, we as a java programmer would view the underlying table as object ...so we would define a Class which would model the above table ... It should be straight forward isn't it ? This is gona be a simple java bean or Plain Old Java Objects... i.e. I would define the properties corresponding to the columns in the table.... how about the data types .. what should be the datatype for user_id ? :)

The only important thing is ...they should be compatible ... the fundamental rules are governed by java.sql.TYPES
here we go with the object definition ....

package com.entities

public class User {

private Long userId;

private String userName;
private String userPassword;
private String userEmail;

/** default constructor */
public User() {
}

public Long getUserId() {
return this.userId;
}

public void setUserId(Long id) {
this.userId = id;
}

public String getUserName() {
return this.userName;
}

public void setUserName(String userName) {
this.userName = userName;
}

public String getUserPassword() {
return this.userPassword;
}

public void setUserPassword(String userPassword) {
this.userPassword = userPassword;
}

public String getUserEmail() {
return this.userEmail;
}

public void setUserEmail(String userEmail) {
this.userEmail = userEmail;
}

}


Now, we have table ready..we have the class ready ...whats next ... ? I ask you a question ... how hibernate would determine ... which class refers which table .. which property of class maps to which column ? does this question makes sense ? of course it does ...

We are going to do next is to have a xml file ..which maps this stuff... and hibernate should be told to use this as the fundamental rules for mappig between the User class and USER table.... ok ?

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
<class name="com.entities.User" table="user">
<id column="USER_ID" name="user_id" type="java.lang.Long">
<generator class="increment"/>
</id>

<property column="USER_NAME" name="userName"/>
<property column="USER_PASSWORD" name="userPassword"/>
<property column="USER_EMAIL" name="userEmail"/>
</class>
</hibernate-mapping>

let us name this file user.hbm.xml .... you can name it the way you like it ... but as a hibernate style ...we would name the mapping files with .hbm.xml suffix.... now the next question ....where you would keep this file ?


Genuine answer is ...keep it anywhere it has to be in classpath :) ... but we generally keep them along the corresponding java beans classes ...
so I would keep it in com.entities package, along with User.java


Hibernate mapping documents are straightforward. I will describe the major elements in the mapping file.
1. <hibernate-mapping> element
The root element of the Hibernate mapping document is the <hibernate-mapping> element. This element has several optional attributes.

2. <class> element
The <Class> element maps the object with corresponding entity [table] in the database. In simple words, the <class> element maps a table with the corresponding class. The <hibernate-mapping> element allows you to nest several persistent <class> mappings, as shown above. It is, however, good practice to map only a single persistent class in one mapping file and name it after the persistent superclass; for example, User.hbm.xml.

3. <id> element

The <id> element defines the mapping from that property to the primary key column. The <id> element represents the primary key column and its associated attribute in the domain object. Mapped classes must declare the primary key column of the database table. Most classes also will have a JavaBeans-style property holding the unique identifier of an instance.

4. <generator> element

The optional <generator> child element names a Java class used to generate unique identifiers for instances of the persistent class. This is like a unique id generator ... Some commonly used generators are:

1. Increment. Generates auto increment numbers of type long, short, or int that are unique.
2. Sequence. Uses a predefined sequence from oracle, DB2, PostgreSQL, SAP DB. The returned identifier is of type long, short, or int.
3. Assigned. Lets the application assign an identifier to the object before. This is the default strategy if no <generator> element is specified.
4. Foreign. Uses the identifier of another associated object.

Let us defer their deep understanding to the knowledge refinement phase :))

5. <property> element
The <property> element declares a mapping between property of the class and the underlying column.

0 comments: