Archive

Archive for the ‘Java’ Category

Integrating Hibernate with Struts1.x

July 2nd, 2010 kumarasamy No comments
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)
Categories: Java, ORM Tags: , ,

Logging in J2EE Applications

June 1st, 2010 kumarasamy No comments
Logging is the one of the most important quality a software developer should have as a practice while coding for their applications. Logging serves as many purpose from debugging the application when a developer encounters an issue, trouble shooting the users issue, when it’s in production mode and can be used to fine tune our application with some performance measures. So logging becomes so important in a Web Application. So what are the ways we can add logging to our application which is developed in J2EE platform, there are many ways to do, they are,
  • Using Logging Framework - Log4J, SL4J, Java Logging API and Apache Commons Logging. These logging framework provides lots of functionality built-in. These frameworks defines three different processors for logging. They are Loggers, Formaters and Appenders. And these frameworks provides many levels for logging also. These frameworks provides many means of organizing your logs like Storing into Files, Database tables and some times these framework will help us in sending the email alerts also. There are many open source loggers can be found here.
  • Custom Developed Loggers - This mayn’t be complete logging solution. Sometimes we may need to code our own way of logging, this depends on our requirement to log. For example We may wanted to just to record only the user actions in all of the screens in an application and the admin needs the screen to see all the action done by that particular user with some more criteria like date etc… This time instead me adding one more framework and cluttering the application configuration, we can simply make use of the existing JDBC connection and store all the actions on the same database where we do store our application data. The other scenario i can think off here is, say for example i’m planning to log many details from each and every request of the user, in this case logging becomes heavier to maintain for the containers, this time we can try use our own loggers with pooling of objects on the user basis.
What are the things should be logged?
There are some categories of information which always has to be logged, they are Error(s) and Exception(s). Apart from these login and logout information, SQL queries and their execution times, parameters if we have any for prepared statement(including Stored Procedures), if we have any interfacing application then the request and response information, basically all the domain objects(internal data structures in the application), each and every user actions like button clicks, session time out for the user session also can be logged for better troubleshooting and debugging purposes. But it’s completely developers duty that they log the IP Address for the Client, Browser Agent, TimeStamp and the user id/information are getting captured in the log information this will make a real big impact on the debugging for web applications.
In my previous experience i have come across some logging mechanisms where they’ve used their own logging tools(basically this made me to write about the custom logging frameworks). Little more details about it.
Using JDBC with DB tables - The basic idea here is have a dB table for user history, store the important actions from the user(s) like button clicks, important queries. But we have to make sure that we are making use of the connection pool, otherwise this becomes costly inside our application and the number of connections shoots up always. The advantage of this approach is easy way of accessing the logs, i.e. a screen inside the same application show this log. Admin of the application can look into these details and can identify few issues of the users. The user’s action sequence can be identified easily. The major drawbacks of this approach is when there is an huge data available as history, then the admin page loading time will become more, the only option to have an archive mechanism to solve this issue.
Using File System -  This approach is like Log4j where we’ll make use of files to write our logs and this can be rotated on daily basis. And this can be divided further more saying the application logs and the DB logs can be separated into two different files. And further more this can be used for each and every module in the application can have two files like application log and database logs. But this approach can be used to log each and every action/request from the user with data. And the naming convention can be on the unique user id. Each user session contains the pool of these objects so that the number of I/O operations are not exceeding the limits. This would be very good approach in logging for a web application since each and every request for the server will be logged for that particular user.
The final important thing here is, what ever the method we follow to log the details we should be able to troubleshoot/debug the applications easily/fastly, even it’s going to be in production. The logging is an very important factor that we should be considering when we think of designing/developing an web application.
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)

Using Hibernate’s HQL

May 28th, 2010 kumarasamy No comments
Hibernate uses a powerful query language called as HQL that is similar to SQL. Compared with SQL, however, HQL is fully object-oriented and understands notions like inheritance, polymorphism and association. Hibernate generates the SQL from these HQL’s and executes against the RDBMS. HQL supports Clauses, Aggregate functions and Subqueries with it’s syntax. Other advantage of using HQL is, it can give us the results as Objects. And the queries written in HQL can be executed in all the databases with out the changing it, so it makes our application most of the time independent of database flavor we choose.We’ll discuss about the clauses and the examples of Clauses.
Clauses in HQL
HQL supports five types of Clauses, they are

  • from Clause
  • where Clause
  • select Clause
  • order by Clause
  • group by Clause
We’ll look at the from clause. And for all of these operation we’ll take the Singer domain class which we have used it in our previous post Simple CRUD Operation Using Hibernate. We have two properties to a Singer which is ID and the Singer Name. We’ll take a closer look at the CRUDTest.listSinger() method, we were using the “from Clause” to select the result from Singer table. We’ll modify that slightly to use the Query to use the from clause. So i’ll be updating listerSinger() method as follows.
			public void listSinger() {
				Session session = FactoryUtil.getSessionFactory().openSession();
				Transaction transaction = null;
				try {
						transaction = session.beginTransaction();
						Query qry = session.createQuery("from Singer singer");
						for (Iterator iterator = qry.iterate(); iterator.hasNext();) {
							Singer singer = (Singer) iterator.next();
							System.out.println(singer.getSingerName());
						}
				}
				catch (HibernateException e) {
					transaction.rollback();
					e.printStackTrace();
				}
				finally {
					session.close();
				}
			}
			
Now, We’ll look at the where clause. The where clause is smilar to where clause in SQL. In HQL Where clause allows us to set the parameters, Compound Path expressions. In case of HQL, the Compound path expressions are making it more useful and easy for the developers too. Consider our Singer example and we are going to add, Event table to store his stage events.This events may have one more attribute called address of the events, which can be put into an other table called address. Now consider the situation of getting all the events performed by a singer, which of the city Bangalore. if some one is asking to get the details of all the singer’s name then i’ll be writing the following query in SQL.
			SELECT sing.singer_name FROM SINGER sing LEFT OUTER JOIN SINGER_EVENTS eve ON eve.singer_id = sing.singer_id LEFT OUTER JOIN EVENT_ADDRESS addr ON addr.event_id = eve.event_id WHERE addr.city = 'Bangalore'
		
Writing these kind of queries is not so easy always and as java developer we won’t be concentrating on writing queries. So HQL provides a easy way to address this using Compound Path Expressions. I can rewrite the above SQL as following using HQL.
		SELECT sing.singer_name FROM SINGER sing WHERE sing.eve.addr.city = 'Bangalore'
	
isn’t that looks easy for us? The other good example i can look at here is, binding the javabean properties directly to HQL’s. This is almost similar to our Prepared Statements in JDBC. Look at the following code snipet,
				Singer singer = (Singer) session.get(Singer.class, singerId);
				singer.setSingerName("Jerry");
				query = session.createQuery(" from Singer sing where sing.name=:singername ");
				query.setProperties(singer);
	
The above code is self explantory, where we set the singer name property using the setProperties() method from Query. We’ll be able to set multiple parameters to it. I suppose this will be really helpful when work with “Dependency Injection”, i.e Inject these values through Spring Config file and call these queries.
The next clause we’ll take it here is, Select Clause. HQL offers may functionalities like SQL queries, We have Aggregate functions, expressions. The most important thing i feel like discussing here is, returning the results as objects, lists and sometimes it can be ad DTO’s also. We’ll consider the above example of getting singer’s who has performed some events in “Banglore”. We’ll add some more parameters to return. We’ll add Event Name and the place of the event to return. We’ll update the CRUDTest.listSinger() to the following,
			public void listSinger() {
				Session session = FactoryUtil.getSessionFactory().openSession();
				Transaction transaction = null;
				try {
						transaction = session.beginTransaction();
						List singerDetails = session.createQuery("select new list(singer.singer_name,eve.event_name) from Singer singer where singer.eve.addr.city='Bangalore' ").list();
						for (Iterator iterator = List.iterator(); iterator.hasNext();) {
							List tempDetail = (List) iterator.next();
							System.out.println(tempDetail.get(0));
						}
				}
				catch (HibernateException e) {
					transaction.rollback();
					e.printStackTrace();
				}
				finally {
					session.close();
				}
			}
			
Basically this returns the list where we have the Singer name and event name. HQL allows us to use the “new” opertor combined with domain objects also. Say for example instead of returning as list, if we may wanted to return as domain object then the code looks like the following,
			public void listSinger() {
				Session session = FactoryUtil.getSessionFactory().openSession();
				Transaction transaction = null;
				try {
						transaction = session.beginTransaction();
						List singerDetails = session.createQuery("select new Singer(singer.singer_name,eve.event_name) from Singer singer where singer.eve.addr.city='Bangalore' ").list();
						for (Iterator iterator = List.iterator(); iterator.hasNext();) {
							Singer tempDetail = (Singer) iterator.next();
							System.out.println(tempDetail.getSingerName());
						}
				}
				catch (HibernateException e) {
					transaction.rollback();
					e.printStackTrace();
				}
				finally {
					session.close();
				}
			}
			
On the same way we use the map also to return the results from DB. For Order by clause and Group by Clause HQL will looks similar to SQL.
Warning
To execute the above code we may need to do a lot of change with the Singer.hbm.xml to accomadate the one-many relationship between Singer and the events. A best alternate could be, we can remove the join tables and return only the singer details.
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 playerPlugin by wpburn.com wordpress themes