Thursday, March 26, 2009

Simple Hibernate Program

Introduction:

Working with object-oriented software and a relational database can be cumbersome and time consuming in today’s enterprise environments. Hibernate is an object/relational mapping tool for Java environments. The term object/relational mapping (ORM) refers to the technique of mapping a data representation from an object model to a relational data model with a SQL-based schema.

Hibernate not only takes care of the mapping from Java classes to database tables (and from Java data types to SQL data types), but also provides data query and retrieval facilities and can significantly reduce development time otherwise spent with manual data handling in SQL and JDBC.

Hibernates goal is to relieve the developer from 95 percent of common data persistence related programming tasks.

Simple example for Understanding of Hibernate:

Place the following jar file in the lib folder
1.antlr.jar
2.cglib.jar
3.asm.jar
4.asm-attrs.jars
5.commons-collections.jar
6.commons-logging.jar
7.hibernate3.jar
8.jta.jar
9.dom4j.jar
10.log4j.jar
11.slf4j-api-1.5.2.jar
12.slf4j-nop-1.5.2.jar
13.slf4j-simple-1.5.2.jar
14.javassist-3.4.GA.jar

your class or bean for storing and retriving Employee details from the database

Employee.java

Your mapping file to map bean attributes with database column names

Employee.hbm.xml

hibernate.cfg.xml

In the above configuration file the property hbm2ddl.auto as create it will create table automatically with the column name as specified in the mapping file names as Employee.hbm.xml. It will drop the table if the specified table already exists.

If you cofigure the property of hbm2ddl.auto as update it will update the table with specified values if the table exists or else it will create a table and insert the values.

The property dialect is to specify the database used. Here Oracle database is used. If you use MySQL then mention the dialect as org.hibernate.dialect.MySQLDialect.

If you set the propery of show_sql to true it will display the query in the console.

Finally, the mapping file should be specified.

Example to insert an Employee details into database

Example to display employee details in the console

Note that in the above example that the query deals with POJO class and its attributes not directly with the database table or column.

Example to update employee details in the database

Example to delete employee details from the database

This is a simple example for understanding about Hibernate and if you have queries raise here and get the solution.

Hibernate Reference book

Hibernate Tutorial

No comments: