Posts Tagged ‘ORM’

Integrating Hibernate with Struts1.x

Friday, July 2nd, 2010
We have got list of post(s) about Hibernate. Today as a next step we’ll try to intergrate with MVC framework. We’ll take the most used one which Struts1.3. For example we’ll take the same Singer Example and we’ll work with that for intergrating with struts also.Since we have the domain object generated already, we can make use of the same domain object to populate the values from DB, when we use the Hibernate.
We just take the examples of listing all the Singers from Singers table. Since we are using Struts1.x, we may need to write the action class and form class. The following code shows Form Class. Since we are going to list all the Singers, then our Form looks like the following.
		package com.techmaddy.form;

		/*
		*  Copyright 2010 - Kumarasamy
		*	kumarasamy@techmaddy.com
		*/

		import javax.servlet.http.HttpServletRequest;

		import org.apache.struts.action.ActionForm;
		import org.apache.struts.action.ActionMapping;

		import com.techmaddy.singer.Singer;

		public class SingerForm extends ActionForm {

			private static final long serialVersionUID = 1L;

			private Singer[] singer =  new Singer[0];

			public Singer[] getSinger() {
				return singer;
			}

			public void setSinger(Singer[] singer) {
				this.singer = singer;
			}

			public void reset(ActionMapping mapping, HttpServletRequest request) {
				singer =  new Singer[0];
			}

		}
	
The DAO class will make a call to DB and returns the results. This is almost very similar to the class CRUDTest.java in Simple CRUD Operation With Hibernate. Instead of my CRUDTest class, we have an DAO Class which gets the data from DB.
My DAO Class looks like the following.
			package com.techmaddy.bo;

			/*
			*  Copyright 2010 - Kumarasamy
			*	kumarasamy@techmaddy.com
			*/

			import java.util.ArrayList;
			import java.util.Iterator;
			import java.util.List;

			import org.hibernate.Session;
			import org.hibernate.Transaction;
			import org.hibernate.Query;

			import com.techmaddy.singer.HibernateSessionFactory;
			import com.techmaddy.singer.Singer;

			public class SingerManager {

				public Singer[] getAllSingers() {
					List singer = new ArrayList();
					Session session = null;
					Transaction tx = null;

					session = HibernateSessionFactory.getSession();

					tx = session.beginTransaction();
					Query qry = session.createQuery("from Singer");
					for (Iterator iterator = qry.iterate(); iterator.hasNext();) {
						singer.add(iterator.next());
					}

					return (Singer[]) singer.toArray(new Singer[0]);
				}

			}
	
The same way, based in the action performed from the screen, we can make a call to Editing and deleting the Singers.The following Images shows the result screen.
Struts-Hibernate Integration
Download
To download the War file for Singer with Struts Integration Click Here
Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)

Simple CRUD Operation With Hibernate

Tuesday, May 25th, 2010
In my previous post Hibernate, the ORM Library for Java, we have seen the General introduction of ORM Tools and how to configure the hibernate to use it in our applications. In this post we”ll look at the simple examples of DB Operations using Hibernate.
Please have all the libraries needed to work with MySQL with Hibernate, the most important libraries are hibernate3.jar and mysqlconnector.jar.(If you are using MyEclipse, that”ll help you in adding those jars). For using the MySQL the hibernate configuration will look like the following.
		<hibernate-configuration>
			<session-factory>
				<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
				<property name="hibernate.connection.url">jdbc:mysql://localhost/Singer</property>
				<property name="hibernate.connection.username">root</property>
				<property name="connection.password">demo</property>
				<property name="connection.pool_size">1</property>
				<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
				<property name="show_sql">true</property>
				<property name="hbm2ddl.auto">create</property>
			</session-factory>
		</hibernate-configuration>
	
For domain class we”ll take the example of Singer, Who performs some stage shows. As of now we”ll add two properties for him, Which is id and the name of the singer. So we”ll have to configure the Singer.hbm.xml file for Singer as follows.
		<hibernate-mapping>
			<class name="com.techmaddy.singer" table="TBL_SINGER">
			<meta attribute="class-description">Domain Object for Singer</meta>
				<id name="singerId" type="long" column="SINGER_ID">
					<generator class="native"/>
				</id>
				<property name="singerName" type="string" column="SINGER_NAME" not-null="true" />
			</class>
		</hibernate-mapping>
	
We can make use of the MyEclipse’’s “Hibernate Reverse Engineering” option from the database perspective, so that we can easily generate the Singer.hbm.xml and Singer.java domain class also.

		package com.techmaddy.singer;

		public class Singer implements java.io.Serializable {

			private Long singerId;
			private String singerName;

			public Singer() {}

			public Singer(String singerName) {
				this.singerName = singerName;
			}

			public Long getSingerId() {
				return this.singerId;
			}

			public void setSingerId(Long singerId) {
				this.singerId = singerId;
			}

			public String getSingerName() {
				return this.singerName;
			}

			public void setSingerName(String singerName) {
				this.singerName = singerName;
			}
		}
		
This above code ss an domain class for Singer, It’’s just nothing but an POJO or we can say an JavaBean. The other important component fo Hibernate is SessionFactory. The SessionFactory provides the session to work with RDBMS. SessionFactory should be created only once per application on web container. SessionFactory can be created many ways, most of the time SessionFactory will be created as a Singleton utility class.By using the following methods, we can creating the SessionFactory, they are
  • An Utility Class with Singleton - A Singleton class with the option to create an SessionFactory and then the object can be made available to JVM.
  • From an Servlet - A servlet which is loaded on startup of the container and the service method pushes the object into an Singleton Utility class
  • Static Block - inside a static block in some sort of Utility Java class that can be used in program code to retrieve SessionFactory

We”ll implement the third option to create the SessionFactory.


		package com.techmaddy.singer

		public class FactoryUtil {

		//Static Session Factory
		private static org.hibernate.SessionFactory sessionFactory;

		private FactoryUtil() {}

		static {

			//Creates the SessionFactory based on the XML Configuration
			Configuration configs = new Configuration();
			sessionFactory = configs.configure().buildSessionFactory();
		}

		public static SessionFactory getInstance() {
			return sessionFactory;
		}

		public Session openSession() {
			return sessionFactory.openSession();
		}

		public Session getCurrentSession() {
			return sessionFactory.getCurrentSession();
		}

		public static void close() {
			if (sessionFactory != null)
				sessionFactory.close();
			sessionFactory = null;
		}
	}
The above code creates the SessionFactory, since the creation of SessionFactory is in Static block, we”ll be able control the creation of SessionFactory object. By this way we””l have the control of creating the session obejcts. The SessionFactory reads the hibernate cfg xml and then it creates the session object for our application. We are all set to go and write our class, to test the hibernate.
Basically we”ll look into the example of CRUD by making use of the Hibernate Session object.
			package com.techmaddy.singer;

			import org.hibernate.HibernateException;
			import org.hibernate.Session;
			import org.hibernate.Transaction;

			public class CRUDTest {

				public static void main(String[] args) {
					CRUDTest crudTest = new CRUDTest();
					Long singer = crudTest.insertSinger("Jason");
					singer = crudTest.insertSinger("Jerry");
					singer = crudTest.insertSinger("Chun");
				}

				public Long insertSinger(String singerName) {
					Session session = FactoryUtil.getSessionFactory().openSession();
					Transaction transaction = null;
					Long singerId = null;

					try {
						transaction = session.beginTransaction();
						Singer singer = new Singer();
						singer.setSingerName(singerName);
						singerId = (Long)session.save(singer);
						transaction.commit();
					}
					catch (HibernateException e) {
						transaction.rollback();
						e.printStackTrace();
					}
					finally {
						session.close();
					}
				return singerId;
			}
		}
When we run this following code, we”ll get the output in the console as follows,this is since we mentioned “show_sql” property in hibernate.cfg.xml to “true”.
Console
After executing this statement, we can check the database for inserted values.

Transaction

The CRUDTest is now hadnling update and delete operations, so the above class has been to changed to the following,

			package com.techmaddy.singer;

			import java.util.Iterator;
			import java.util.List;
			import org.hibernate.HibernateException;
			import org.hibernate.Session;
			import org.hibernate.Transaction;

			public class CRUDTest {

				public static void main(String[] args) {

					CRUDTest crudTest = new CRUDTest();
					Long singer = crudTest.insertSinger("William");
					singer = crudTest.insertSinger("Jerry");
					Long tempSinger = singer;
					singer = crudTest.insertSinger("Stanley");
					crudTest.listSinger();
					crudTest.updateSinger(singer,"Chun");
					crudTest.deleteSinger(tempSinger);
				}

				public Long insertSinger(String singerName) {

					Session session = HibernateSessionFactory.getSessionFactory().openSession();
					Transaction transaction = null;
					Long singerId = null;
					try {
						transaction = session.beginTransaction();
						Singer singer = new Singer();
						singer.setSingerName(singerName);
						singerId = (Long)session.save(singer);
						transaction.commit();
					}
					catch (HibernateException e) {
						transaction.rollback();
						e.printStackTrace();
					}
					finally {
						session.close();
					}
					return singerId;
				}

				public void listSinger() {
					Session session = HibernateSessionFactory.getSessionFactory().openSession();
					Transaction transaction = null;

					try {
						transaction = session.beginTransaction();
						List singers = session.createQuery("FROM Singer").list();
						for (Iterator iterator = singers.iterator(); iterator.hasNext();) {
							Singer singer = (Singer) iterator.next();
							System.out.println(singer.getSingerName());
						}
						transaction.commit();
					}
					catch (HibernateException e) {
						transaction.rollback();
						e.printStackTrace();
					}
					finally {
						session.close();
						}
					}

					public void updateSinger(Long singerId, String singerName) {
						Session session = HibernateSessionFactory.getSessionFactory().openSession();
						Transaction transaction = null;

						try {
							transaction = session.beginTransaction();
							Singer singer = (Singer) session.get(Singer.class, singerId);
							singer.setSingerName(singerName);
							session.update(singer);
							transaction.commit();
						}
						catch (HibernateException e) {
							transaction.rollback();
							e.printStackTrace();
						}
						finally {
							session.close();
						}
					}

					public void deleteSinger(Long singerId) {
						Session session = HibernateSessionFactory.getSessionFactory().openSession();
						Transaction transaction = null;
						try {
							transaction = session.beginTransaction();
							Singer singer = (Singer) session.get(Singer.class, singerId);
							session.delete(singer);
							transaction.commit();
						}
						catch (HibernateException e) {
							transaction.rollback();
							e.printStackTrace();
						}
						finally {
							session.close();
						}
					}
				}
All Transaction
Final Result
Download
To download the War file for Singer Click Here
Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)

Hibernate, the ORM Library for Java

Wednesday, May 5th, 2010
Object-relational mapping
Which helps you in converting the relational databases to object oriented programming languages,which help a developer to keep the persistence of the domain object.Basically ORM tools will provide the bridge between the database and the application by storing application objects in the database for the developer, rather than requiring the developer to write and maintain mountains of code to store and retrieve objects.
In other words we can say, Object/relational mapping (ORM) is the process of persisting objects in a relational database. ORM bridges the gap between object and relational schemas, allowing your application to persist objects directly without requiring you to convert objects to and from a relational format.There are List of ORM softwares for Java.
All among the list of Software’s Hibernate, requires a small amount of metadata for each persistent object. Hibernate operates independently of application architecture, allowing it to be used in various applications. It provides full object/relational mapping,meaning that it supports all the available object-oriented features that relational databases lack.
Hibernate - Free GPL,ORM Library
The primary feature’s are,

  • Mapping - Hibernate maps the java classes a.k.a domain objects to db tables through xml configuration. This xml configuration tells the Hibernate how to persist these objects.
  • Persistence - Hibernate provides transparent persistence for Plain Old Java Objects (POJOs). The only strict requirement for a persistent class is a no-argument constructor, not necessarily public
  • Hibernate Query Language (HQL) - Hibernate provides a SQL inspired language called Hibernate Query Language (HQL) which allows SQL-like queries to be written against Hibernate’s data objects. Criteria Queries are provided as an object-oriented alternative to QL.
Mapping XML
Mapping definitions, also called mapping documents, are used to provide Hibernate with information to persist objects to a relational database.The mapping files also provide support features, such as creating the database schema from a collection of mapping files.The mapping file tells Hibernate what table in the database it has to access,and what columns in that table it should use.
<?xml version="1.0"?>
<hibernate-mapping package="com.techmaddy.domain">
[...]
</hibernate-mapping>
Now we’ll try to add the domain object Book, which holds Author, Edition. By this we are telling the Hibernate to persist this object and map from RDBMS to java code.So the above mentioned XML will be changed to the following.
<?xml version="1.0"?>
<hibernate-mapping package="com.techmaddy.domain">
<class name="com.techmaddy.domain.Book" table="HBD_BOOKS">
	<property  name="authorName" type="string" column="HBD_AUTHNAME" not-null="true" />
	<property  name="edition" type="string" column="HBD_EDITION" not-null="true" />
</class>
</hibernate-mapping>
From the above mentioned config file, we’ll end up generating the domain class, with two member. The name attribute tells the hibernate to generate the getter and setter for that property. So in our exmaple it’ll be like getAuthorName() and getEdition(). And the same for setters also. Now we’ll see one more scenario, every domain object we add may have the primary key associated. Most of the time this key will be autogenerated, the property tag doesn’t have any special attribute to specify this. So we are going to make use of the id tag, which tells the hibernate, this column is the primary key and it’s going to be generated automatically. So i’m going to add some more tags in the above xml.
<?xml version="1.0"?>
<hibernate-mapping package="com.techmaddy.domain">
<class name="com.techmaddy.domain.Book" table="HBD_BOOKS">
	<id name="id" column="EVENT_ID">
		<generator class="native"/>
	</id>
	<property  name="authorName" type="string" column="HBD_AUTHNAME" not-null="true" />
	<property  name="edition" type="string" column="HBD_EDITION" not-null="true" />
</class>
</hibernate-mapping>
The generator creates the primary key value for the persistent class.Native generators provide portability for mapping documents since the framework can determine the generator method supported by the database. Generators using the native class will use identity or sequence columns depending on available database support. If neither method is supported, the native generator falls back to a high/low generator method to create unique primary key values.
The other generators are Assigned and Select. The Assign lets you generate and assign the object ID.Select generator, which retrieves the primary key value by selecting a value from a database trigger. The generator type you choose determines its behavior based on the underlying database.
Hibernate Components & Configuration
Hibernate can be used with Web Application and with an Standalone java applications also. The below image will give you the basic components of Hibernate.
hibernate.cfg.xml & hibernate.properties - These are used to configure the hibernate service. Both these files does the samething.When these two are present in the classpath, then hibernate.cfg.xml will overrides the hibernate.properties file. Basically these files are used to basic connection info, whcih we are going to use it in our application.
Session Factory - SessionFactory allows application to create the Hibernate Sesssion by reading the configuration from hibernate.cfg.xml file.It implements a design pattern, that ensures that only one instance of the session is used per thread.
Session - represents a single-threaded unit of work.Session instances are your primary interface to the Hibernate persistence service.
By using the Hibernate we are going to connect to DB, So the Hibernate should be instructed to pick the drivers and get the connection.The following XML, will gives us the skeleton of the hibernate.cfg.xml
		<hibernate-configuration>
			<session-factory>
				[...Properties for JDBC Connection]
				....
				[...]
				[..Mapping resources]
				....
				[...]
			</session-factory>
		</hibernate-configuration>
For the above hibernate configuration, we’ll try to add the properties for HSQL database. Then sessionfactory tag will becomes the following
			<session-factory>
				<property name="connection.driver_class">org.hsqldb.jdbcDriver</property>
				<property name="connection.url">jdbc:hsqldb:hsql://localhost</property>
				<property name="connection.username">sa</property>
				<property name="connection.password"></property>
				<property name="connection.pool_size">1</property>

				<property name="dialect">org.hibernate.dialect.HSQLDialect</property>
			</session-factory>
This configures the connection properties, along with the SQL Dialect. The SQL dialect tells the hibernate that we are using a specific JDBC drivers. In this example we are going to make use of HSQL DB.The List of dialects are available here.
Now we’ll add the domain object mappings to hibernate.cfg.xml. The following syntax shows how to add an mapping xml for an domain object.
			<mapping resource="com/techmaddy/domain/Book.hbm.xml"/>
Adding this completes the hibernate basic configuration, along with this we may need to add the libraries for the hibernate.Creating the Startups for creating the session factory and helpers we’ll be dicuss in the next article.
Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)
Get Adobe Flash player