Wednesday, October 8, 2008

Simple Hibernate Example with ANT script

The Following Example is shows how to save data into database for that you required the follwoing components
1.hibernate mapping file(hbm.xml)
2. simple PlainOldJavaObject (POJO) class with setters and Getters
3.required jar files for hibernate nad database driver
4.Ant script to run the program
5. simple Class with main() method

1.First i have Person table in database with the following fields
sql-query for creating table: create table person (personid int primary key,name varchar2(30),age int, weight int);
2. creating person.hbm.xml
<?xml version="1.0" encoding="UTF-8"?/>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd/>
<hibernate-mapping package="com.siva">
<class name="Person" table="person">
<id name="personId" type="java.lang.Long">
<generator class="increment"/>
<id/>
<property name="name" type="string"/>
<property name="age" type="java.lang.Long"/>
<property name="weight" type="java.lang.Long"/>
<class/>
<hibernate-mapping/>
In the above hbm file you have id generator class="increment" for id you no need to insert explicit value hibernate it self give id to you .
3. simple POJO class of Person

package com.siva;
public class Person
{
private Long personId;
private String name;
private Long age;
private Long weight;
public Long getPersonId() {
return personId;
}
public void setPersonId(Long personId) {
this.personId = personId;
}

public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Long getAge() {
return age;
}
public void setAge(Long age) {
this.age = age;
}

public Long getWeight() {
return weight;
}
public void setWeight(Long weight) {
this.weight = weight;
}
}
Now for hibernate we have all are in place except configuration which database we need to point and what is driver for that so writing another xml file for this we mention all this in The following class itself
4. SimpleHibernateTest class as following
package com.siva;
import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.Transaction;import org.hibernate.cfg.Configuration;import org.hibernate.cfg.Environment;
public class SimpleHibernateTest
{
public static void main(String[] args)
{
Transaction tx = null;
try
{
Configuration cfg = new Configuration();
cfg.setProperty(Environment.AUTOCOMMIT ,"true" );
cfg.setProperty (Environment.DRIVER, "oracle.jdbc.driver.OracleDriver");
cfg.setProperty(Environment.DIALECT, "org.hibernate.dialect.Oracle9Dialect");
cfg.setProperty(Environment.USER, "database username");
cfg.setProperty(Environment.PASS,"database password");
cfg.setProperty(Environment.URL, "jdbc:oracle:thin:@localhost:1521:SID");
//here SID is database name it is xe for oracle 10G
System.out.println("connected to databse " + cfg.getProperty(Environment.URL));
cfg.addFile("person.hbm.xml");
Person p = new Person();
p.setName("siva");
p.setAge(26L); p.setWeight(63L);
SessionFactory sessionFactory = cfg.buildSessionFactory();
Session session = sessionFactory.openSession();
tx = session.beginTransaction();
session.save(p);
System.out.println("successfully save the record in database");
tx.commit();
session.close();
} //try end
catch(Exception ex)
{
ex.printStackTrace();
tx.rollback();
}//catch end
}//main method end
}//class end
Now we run this program in two ways
1. we run this through command prompt like noramal program
javac com.siva.SimpleHibernateTest.java
but we need required jar files so all jar files we need to keep in classpath
or if we using eclipse no need to bother about class path you can all jar files to build path of
project properties.
2. writing ANT file through that we can run the program
if we want to run the program through ANT we need ANT bin directory to path.
the follwoing ANT XML file

<project name="test" default="compile">
<property name="sourcedir" value="${basedir}"/>
<property name="targetdir" value="${basedir}/bin"/>
<property file="build.properties"/>
<path id="libraries">
<fileset dir="${librarydir}">
<include name="*.jar">
<fileset>
<fileset dir="${OraLib}">
<include name="*.jar">
</fileset>
</path>
<target name="clean">
<delete dir="${targetdir}"/>
<mkdir dir="${targetdir}"/>
</target>
<target name="compile" depends="clean, copy-resources">
<javac srcdir="${sourcedir}"
destdir="${targetdir}"
classpathref="libraries"/>
</target>
<target name="copy-resources">
<copy todir="${targetdir}">
< fileset dir="${sourcedir}">
<exclude name="**/*.java"/>
</fileset>
</copy>
</target>
<target name="run" depends="compile">
<java fork="true" classname="com.siva.SimpleHibernateTest" classpathref="libraries">
<classpath path="${targetdir}"/>
</java>
</target>
</project>

In the above build.xml file there is one propety file=build.properties
this is for to give the location of jar files
where your hibernate jar files and database jar fiels
like the following
librarydir = C:/Hibernate Training/hibernate-3.1.2/hibernate-3.1/lib
OraLib = C:/oracle/ora90/jdbc/lib
After completing the above steps
just locate where is your build.xml file
for eg: c:\test\build.xml
come to command prompt and type like the following
c:\test> ANT
automatically it will compile because in your nat file you written Default as compile
once successful compilation you need to rubn for that
in the command prompt type the following
c:\test>ANT run
it will executs and insert the data into database.
This is the simple Hibernate example to start to learn hibernate.

AddToAny

Contact Form

Name

Email *

Message *