Archive for June 2009

Increment with hibernate generator

This is continuation of my previous post.

We discussed with different type of generators for primary keys and we have seen an example with ‘assigned’ previously. We can see ‘generator‘ in this post.

RoseIndia says we shouldnt use this in clustered invironment.

Create a table using the following structure.

BOOK-table structure

BOOK-table structure

Let your DTO be like this

package hib;

public class Book {
 private long bookID;
 private String bookName;
 public long getBookID() {
 return bookID;
 }
 public void setBookID(long bookID) {
 this.bookID = bookID;
 }
 public String getBookName() {
 return bookName;
 }
 public void setBookName(String bookName) {
 this.bookName = bookName;
 }
}

Add the following entries to contact.hbm.xml inside the root element

<class name="hib.Book" table="BOOK">
 <id name="bookID" type="long" column="ID">
 <generator></generator>
 </id>
 <property name="bookName">
 <column name="BOOKNAME"></column>
 </property>
 </class>

Let your client program be as follows

package hib;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class IncrementTest {

 /**
 * @param args
 */
 public static void main(String[] args) {
 Session session=null;
 try {
 SessionFactory sessionFactory=new Configuration().configure().buildSessionFactory();
 session = sessionFactory.openSession();
 Transaction tx = session.beginTransaction();
 System.out.println("Transaction beginning");
 Book book = new Book();
 book.setBookName("LIVE LA FRANCE");
 session.save(book);
 System.out.println("book stored");
 tx.commit();
 } catch (HibernateException e) {
 e.printStackTrace();
 }finally
 {
 if (session!=null){
 session.flush();
 session.close();
 }
 }
 }
}

And be happy, your inserted the records with auto incrementing ID :)

book console

book console

book result

book result

Show light on Hibernate mapping file

This is in continuation of my previous post.

Lets take the hibernate mapping file and get to the tags used in that file.

<?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="hib.Contact" table="CONTACT">
 <id name="id" type="long" column="ID" >
 <generator/>
 </id>

 <property name="firstName">
 <column name="FIRSTNAME" />
 </property>
 <property name="lastName">
 <column name="LASTNAME"/>
 </property>
 <property name="email">
 <column name="EMAIL"/>
 </property>
 </class>
</hibernate-mapping>

We could see some XML tags tries forms this mapping. Their explanations are given below.

hibernate-mapping

Root element of this mapping

class

maps the java class and SQL table

id

This will handle the primary key constraint. In addition this is the unique representation of an object.
Attributes of ID elements are given below.

name:

The property name used by the persistent class.

column:

The column used to store the primary key value.

type:

The Java data type used.

unsaved-value:

This is the value used to determine if a class has been made persistent. If the value of the id attribute is null, then it means that this object has not been persisted.

generator

This is the notification to generate the primary key. The following values to this attribute decides the type of generator

Increment:

generate primary keys of type long, short or int that are unique only. It should not be used in the clustered deployment environment.

Sequence:

Hibernate can also use the sequences to generate the primary key. It can be used with DB2, PostgreSQL, Oracle, SAP DB databases.

Assigned

Assigned method is used when application code generates the primary key.

property

The property elements define standard Java attributes and their mapping into database schema. The property element supports the column child element to specify additional properties, such as the index name on a column or a specific column type

Hibernate demo

hibernate

hibernate

This post will help you to setup the environment to write your first hello world program with Hibernate!

  1. Get the hibernate distribution from their website. (as of now, I have hibernate-distribution-3.3.2.GA-dist.zip with me)
  2. Download the jars for commons-logging, asm and JDBC driver for your database.
  3. Start a java project in eclipse.
  4. Add all jars in hibernate distribution and other libraries mentioned in step 2.
  5. Prepare your hibernate configuration file
  6. Prepare your Data Transfer Object (DTO) and SQL table
  7. Prepare your hibernate mapping file for your DTO
  8. Start JDBC calls.

Library files needed

Almost all jars are being distributed. I have downloaded commons-logging and asm extra. Then I added the JDBC driver for mysql later. Nothing more (you want more????)

hibernate-jars

hibernate-jars

Preparation of Hibernate Configuration File

This file contains the DB configuration detail for Hibernate. Generally it follows the structure like this.

<?xml version=’1.0′ encoding=’utf-8′?>
<!DOCTYPE hibernate-configuration PUBLIC
“-//Hibernate/Hibernate Configuration DTD//EN”
“http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd”>

<hibernate-configuration>
<session-factory>
<property name=”hibernate.connection.driver_class”>com.mysql.jdbc.Driver</property>
<property name=”hibernate.connection.url”>jdbc:mysql://localhost/test</property>
<property name=”hibernate.connection.username”>root</property>
<property name=”hibernate.connection.password”></property>
<property name=”hibernate.connection.pool_size”>1</property>
<property name=”show_sql”>true</property>
<property name=”dialect”>org.hibernate.dialect.MySQLDialect</property>
<property name=”hibernate.hbm2ddl.auto”>update</property>
<!– Mapping files –>
<mapping resource=”contact.hbm.xml”/>
</session-factory>
</hibernate-configuration>

name this as hibernate.cfg.xml and save it to your ’src’ or source folder. On compilation it should go to your bin or classes or any other target folder.

Preparation of DTO and SQL table

Create  a table in your DBMS using the following structure

table structure

table structure

Write a java class that serves as the DTO for this table.

package hib;

public class Contact {
private String firstName;
private String lastName;
private String email;
private long id;

public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
}

Preparation of hibernate mapping file for SQL table

We mentioned about mapping resource file. we need to create that file now. This is to tell the hibernate about the mapping between java and SQL table.

<mapping resource=”contact.hbm.xml”/>

Another XML is created as follows and named it as contact.hbm.xml

<?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=”hib.Contact” table=”CONTACT”>
<id name=”id” type=”long” column=”ID” >
<generator/>
</id>

<property name=”firstName”>
<column name=”FIRSTNAME” />
</property>
<property name=”lastName”>
<column name=”LASTNAME”/>
</property>
<property name=”email”>
<column name=”EMAIL”/>
</property>
</class>
</hibernate-mapping>

Start Quering with Hibernate

This is the final step. Write a java program that invokes Hibernate and insert data into contact table.

package hib;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class FirstExample {

/**
* @param args
*/
public static void main(String[] args) {
//Hibernate Session is the main runtime interface between a Java application and Hibernate
Session session=null;
try {
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
session = sessionFactory.openSession();
System.out.println(“Inserting record”);
Contact contact = new Contact();
contact.setId(1);
contact.setFirstName(“Pandian”);
contact.setLastName(“R”);
contact.setEmail(“abc@def.com”);

//save the contact information to the database
session.save(contact);
System.out.println(“End”);
} catch (HibernateException e) {
e.printStackTrace();
}finally
{
if (session!=null)
{
session.flush();
session.close();
}
}
}
}

Yes, Now we can start our program and see how the data is getting inserted.

console printing

console printing

Nice na.

Keep querying!

Ref: http://www.roseindia.net/hibernate/runninge-xample.shtml