Search This Blog

Friday, 28 December 2012

In our previous post we saw the Criteria API at its simplest. No select clauses or where clauses. Just the from clause. However without the ability to apply conditions, Criteria as a feature would be of very limited use.

Wednesday, 26 December 2012

Until now I have used HQL in all the posts we have seen. I decided to go ahead and try the Criteria API. With criteria you create your queries programmatically and not via Strings. In the HQL examples the simplest Query was the select * query.

Sunday, 23 December 2012

It is often the case that we need to execute a query based on the results of another query. One way would be to execute the first query, get the results, parse and use them for the second query. The concern here is that since we are not concerned with results of the first query why should we have the application handle that logic ? Instead why not have the database process the two queries together and return to the application only the results of the second query. The results that the application is actually interested in. This can be achieved using inner queries or sub queries.

Tuesday, 18 December 2012

The Spring Web Services project is used for creating document-driven Web services. I decided to create a simple web service that takes a value and returns a value (i.e. no logic - just data transfer) .

Wednesday, 12 December 2012

Exceptions occur. And when they occur in a web application, it leaves us developers looking very stupid. An Apache Tomcat page showing a stack trace and 500 in bold words makes it even worse for us. Graceful handling of exceptions in a web application makes things a tad better.

Monday, 10 December 2012

While studying HQL I came across the following statement:"HQL and JPA QL ignore any fetching strategy defined in the mapping. But the global fetch plan is not ignored"
What is the strategy and what is the plan here ?

Saturday, 8 December 2012

In the previous example we saw the aggregate Functions supported in HQL. But reporting is also dependent on grouping. Examples would be max scores of students grouped by their class, most expensive items sold in a shop grouped by material etc.

Thursday, 6 December 2012

We have been testing out the varied hql functions till now. But what if we want aggregation ?
Aggregate queries are almost always required in applications. Getting the most expensive, the last logged, total hits... whenever any statistics or reporting screens come up, the aggregate queries show up. I decided to start with count functionality:

Sunday, 2 December 2012

In an earlier post we saw how using Spring's ApplicationContext we were able to access and load resources. However having that the ApplicationContext auto-wired in your class so as to allow you to use the Resource Loading functionality may seem a bit of an overkill. We after only need the ability to load resources. So ApplicationContext is out.

Thursday, 29 November 2012

We often come across scenarios wherein we need to upload a file and save it on some persistent storage. We also then have to provide code for downloading the file - this involves processing the request, reading the file - from database or file system and writing it back to the response.

Tuesday, 27 November 2012

We have seen the various capabilities provided by the ApplicationContext. These include I18N, property file loading and event publishing. In this post we shall look at another utility functionality provided by the ApplicationContext - access to low-level resources.

Any web application will need the ability to process request parameters. Spring provide support for direct access to request parameters. But how do we get to the Request object ? Or can we manage without it ?

Sunday, 25 November 2012

There could be a scenario where we need that records from one database to be copied to another database.
Maybe we have an application and we would like to copy its data into another database for analysis. It could be that running export scripts is not an option. Hibernate in this case provides us with the ability to read the data from the table in one database and insert it into another table in the second database. Or to put things better, Hibernate allows us to replicate the objects.

Monday, 19 November 2012

I was looking at the request and response headers in our application the
other day. I noticed that the Browser request included the
Accept-Encoding header. The values indicated my browser was capable of
handling zipped responses.

Saturday, 17 November 2012

OK, this is a little late. I needed to use inheritance and was going across the earlier posts - as I barely remembered how I had done inheritance in the first place. As I looked at the four techniques and the mutated enhancement provided by Hibernate I saw certain things that I had failed to note down the last time.

Sunday, 11 November 2012

As we have seen, The Hibernate Entities that we load in a persistence context may be made of proxies and collection wrappers. The simplest way to initialize these proxies would be to call any of the data getter methods (except Identifier).

Friday, 2 November 2012

In our previous posts we saw how Hibernate allows the use of eager fetching for collections. We also saw that with more than one collection having eager fetch enabled, how the Cartesian product problem was encountered. But this problem will never occur with Bags. Why? Because bags do not support this feature.

Wednesday, 31 October 2012

We all write code. But how many of us write clean well formatted code ? Do we care if our classes are correctly indented ? Does it affect us when our IDE shows tiny yellow warnings? Warnings that scream "unused variable" or "unchecked code" ?

Wednesday, 24 October 2012

In the previous post we saw HQL 's support for inner joins. With inner joins, a rows is returned when there is at least one row from both tables that matches the join condition. However it may be needed that rows are returned even when there are no matches through the join criteria.

Saturday, 20 October 2012

In the rich object model that Hibernate provides us, it allows us to create object associations. These associations which represent records in other tables would be a weak functionality if there was no query support for them.

Thursday, 11 October 2012

In the previous few posts we saw how to use Spring's transaction management.We saw declarative and programmatic support of transactions in Spring. In case of Spring's declarative transaction management using annotations, there are five main attributes that matter:

Monday, 8 October 2012

I recently had the opportunity to work on a mobile project where I faced a whole set of different challenges. All my previous experience involved developing server applications for the web. So when I had to write a REST based API for mobile application we were faced with some interesting challenges.

Thursday, 4 October 2012

We saw in our earlier posts how working with TransactionProxyFactoryBean resulted in large configuration files. Even with the abstract bean technique we still are dealing with verbose configuration. As of version 2.0. Spring has come up with using advises to manage transactions.

Monday, 1 October 2012

In the previous post we saw how to use TransactionProxyFactoryBean. For every class that needs transactional behavior, we need to add one such bean that will act as the proxy. For a big application this is a lot of xml definition. The Spring In Action book shows how this code can be reduced by using abstract beans.

Saturday, 29 September 2012

In the previous post we saw how Spring managed caching via proxies. It follows a similar route to achieve transaction management in a very transparent way. Spring supports programmatic and declarative transactions. Declarative uses aspects and therefore proxies and is therefore achieved in a very transparent manner.

Tuesday, 25 September 2012

Many a times we come upon the need for using caching in our code to improve performance. In my very first IT project we had done caching by writing our own code involving maps, generics and some get put calls. Now we know about readily available third party cache providers and Spring fortunately provides integration for several of these.

Sunday, 23 September 2012

When building a complex application with Maven it is normal to split the code among multiple projects. Every project has its own pom file
and we use a parent pom file to build all projects in the process generating our final build or deployment artifact.
The problem observed is that the different projects have their own dependencies.

Wednesday, 19 September 2012

A few days back we had a code review and one of the concerns raised was "too many logs".
The statement made was : Too many logs in code result could in memory issues.
This was the first time somebody had come with such a feedback. Most of the time it was absence of logs that was the common concern. I decided to spend some time analyzing the complaint.

Friday, 14 September 2012

We have been dealing with Hibernate objects that represents table records. In the inheritance posts we saw how to fetch records by referring to the base class. This would result in all sub class objects being fetched. In Java all classes extend the Object class.

Wednesday, 5 September 2012

In our previous post we saw how to use the JDBC templates to retrieve data. The template included wrappers to return scalar values from execution of SQL queries. For example consider the method from the previous example:

Friday, 24 August 2012

In the last few posts we saw how we could use Spring to create data-sources to interact with the databases. However we never wrote any code to actually do anything in the database. Spring as discussed earlier provides integration via direct JDBC and also via ORM frameworks. We shall start by investigating Spring's JDBC integration mechanism.

Saturday, 18 August 2012

I am yet to work in a project where database connectivity is not required. Spring has covered this area of development too, providing a series of templates and DAOs. In most cases, the techniques provided by Spring need to use a data-source to connect to the database.
I lifted this definition from the IBM site

A data source is associated with a JDBC provider, which supplies the driver
implementation classes that are required for JDBC connectivity with your specific
vendor database. Application components transact directly with the data source
to obtain connection instances to your database.

Saturday, 11 August 2012

With Spring it becomes necessary to configure our beans. This at times involves setting sensitive information in our XML files. In case of database connectivity it would be a username or password. People are not comfortable with this kind of details being available in their war files.

Friday, 10 August 2012

In the previous post we saw how Spring's ApplicationContext provided for event publishing and listening. The default listener that Spring implements is synchronous. The publish method will wait until the methods of all the listeners have completed successfully. This kind of blocking behaviour may not be suitable for all scenarios.

Sunday, 5 August 2012

There could be a scenario wherein we need an association to be always available whenever an Entity is loaded. In this case the additional select queries that are fired are a performance loss. We could tell Hibernate to fetch the entity and the association in a single call to the database.

Friday, 3 August 2012

We have seen that the default fetch strategy for lazy Collections can result in an N+1 problem. We saw how to improve this using the batch size setting. Here also however the query count can end up being a little high.
Hibernate also allows all the Collections to be retrieved in a single query when a single collection is accessed. Thus as opposed to a reduced query count that we get via batching, in this case it is exactly 1 additional query.

Wednesday, 1 August 2012

In our previous example we saw how a default fetch strategy(fetch = "select") could result in N+1 selection problem for Hibernate Associations. One way to solve this problem would be to use batch-size property

Saturday, 28 July 2012

Consider our simple Book and Shelf relation. Every shelf has a collection of Books. As we have not applied any optimization strategies, when we request for a Shelf object from the database, a Shelf proxy is loaded. Then when we access a scalar property (like code) the Shelf scalar properties get loaded using a select query. The Book set is represented by a proxy. Now if we try to access the collection a second fetch is needed.

Wednesday, 25 July 2012

As we saw in our earlier post, Hibernate allows us to lazily load columns in a table row using interception. Interception is used instead of proxies. Consider our Book- Shelf relation. If we wish to replace the Shelf proxy and instead using interception then the hbm files would have the following change:

Tuesday, 24 July 2012

Hibernate uses proxies to ensure that the data is fetched only on a need basis. So if we have a Shelf class that has a set of books, the loading of a shelf object will not load the Book set. Instead a collection proxy will be assigned to the field. It is only when we access the methods of the collection, that the actual fetch occurs.

Saturday, 21 July 2012

Our audit interceptor had several instance members that it used for audit management. For example there was the Set that kept track of all the new entities. What would happen of two threads simultaneously operate on the set. Or in a more general sense, is our interceptor thread safe ? Is it necessary for it to be thread safe ?

Wednesday, 18 July 2012

One of the most popular uses of Interceptors is to log object creations/insertions and deletions. Interceptors allow you to transparently log these state changes and manage the audit trail for an entity.

Monday, 16 July 2012

In the previous post we created a simple Interceptor that logged different operations to the console when they occurred. For testing I created an Entity class that has a one-to-one relation and a collection and decided to test out various operations on it.

Saturday, 14 July 2012

Spring's ApplicationContext provides the functionality to support events and listeners in code. Spring allows us to create listeners in the code. We can create beans that listen for events which are published through our ApplicationContext. This is achieved via the ApplicationEventPublisher interface.

Friday, 13 July 2012

The one thing we see in logs when we use Hibernate is the Question Mark. The question mark makes its appearance in all queries generated whether you use HQL or Criteria or do a load on the object identifier. If we need to debug a query, we need to actually copy the values from bind parameters and then replace them for the question marks. This (and I am sure developers will agree with me ) is a pain. Real PAIN.

Tuesday, 10 July 2012

Hibernate 3.x is built on the concept of events and listeners.To deal with the different operations like loading an object, saving an object, Hibernate creates events. There exists listeners in the Hibernate framework listening for these events.

Tuesday, 3 July 2012

One of the advantages of using the application context is that we can load locale specific messages using the ApplicationContext. More simply put Spring includes Localization and Internationalization support.

Saturday, 30 June 2012

Much of what Hibernate does, happens in the background and the application is not aware of the same. For example dirty checking of entities and scheduling sql update queries for the modified objects is something that Hibernate manages on its own.This is very good in a way, because it removes the amount of code we need to write.

Thursday, 28 June 2012

I think everybody has at some point come across views in Database.Views generally represent a subset of the data contained in a table. A common scenario is one wherein we use soft deletion . For example instead of actually deleting an entity, we have a flag column in the row which we set as true indicating the entity has been deleted. We then create a view to access all the "alive" records.Views thus provide us a filtered access of data in the table.(This is only one of its uses.) Hibernate provides something similar called dynamic views.

Monday, 25 June 2012

In an earlier post I used the ScrollableResults object along with a session to batch multiple operations. In this case I had to manually flush and clear the session after every n SQL operations to prevent my persistence cache from having a memory overflow.
Hibernate also offers an alternative type of Session where it counts on the user to mange the SQL updates on his own.

Tuesday, 5 June 2012

These kind of queries that results in multiple records being updated are termed bulk updates.Hibernate allows us to do the same too. Consider the below code that updates the name column of all Entity records

Saturday, 2 June 2012

There are often scenarios in our application wherein we need to perform batch updates. For example if there was a need to update the zip code of all records in Address table a batch update would be a very good way to achieve the same. A single update SQL query would ensure that the job is done at the database level.
However there arise complications in big applications wherein the update operation would be much more complex then a singe update query or the code complexity better handled in java then in a stored procedure.

Sunday, 29 April 2012

The Spring Container does not have to instantiate beans via using the new keyword. Some times objects are created from factories. There are two ways to achieve the same - via a static factory method or via an instance factory method.

Tuesday, 24 April 2012

In earlier post we saw how Spring allowed us to define custom init and destroy methods - both via configuration and via code.As we are working with cars, we will need to check the engine on all cars before use and clean the car after use.

Monday, 23 April 2012

In our previous post we saw how the Spring container used custom initialization and destroy methods. An alternative way to achieve the same is to use the InitializingBean and DisposableBean Interfaces.

Saturday, 21 April 2012

It is possible that we may need to execute some initialization code when the bean has been initialized successfully by the Spring Container. We saw that the bean life cycle has several methods that can be used to initialize our bean.

Thursday, 19 April 2012

In the previous post we saw the Bean life cycle. Consider the two interfaces BeanNameAware and BeanFactoryAware. The first one makes the object aware of their bean name in a bean factory. The second interface gives the bean access to the Bean Factory that created it.

Saturday, 7 April 2012

As a part of its default fetch strategy, Hibernate uses proxies for collections and all associations when we get an Entity from the database. The proxies have only their id set with access to any other property triggering a further select statement. The idea here is to only hit these tables when the data is needed. But the behavior varies slightly for one to one associations.

Tuesday, 3 April 2012

Hibernate has an attribute called lazy. This makes an appearance in various parts of the hbm file. The first point is the class element. (To try these properties, I am using the same Book- Shelf example from an earlier post.)

Saturday, 24 March 2012

In the previous post we saw the real difference between the load and get methods of the session. We saw that load() works with proxies and get() works with actual database entities.But this behaviour changes completely when the persistence context comes into picture.

Friday, 23 March 2012

This has to be one of the most popular questions asked in hibernate interviews: What is the difference between get() and load() method ?
Hibernate provides us with the two methods to load a persistent entity from the database. These signatures are session.get(Class, Serializable) and session.load(Class, Serializable). Both methods take a class variable and an identifier object and return an instance of the Entity class.

Monday, 19 March 2012

In our previous post we saw how to transition a detached object back to a persistent state. Is it possible to delete an entity from the database if it is not associated with any session? Would Hibernate throw an exception or would the delete succeed? Or would the code simply crash ? The best way to be sure is to try it out on our own :

Sunday, 11 March 2012

In the posts so far we have been defining our beans and configuring them using configuration files. However this results in very large XML files. Spring allows the properties of beans to be automatically wired based on the name of the property or some other conditions.

Friday, 9 March 2012

In the last posts we saw Springs ability to inject collections - both simple value types and complex object types. But just because Spring allows us to configure objects does not mean we have to always configure them. For e.g. there could be a Singer class that uses constructor injection to wire its "song" property. But what do you do if you don't have a song ?

Wednesday, 7 March 2012

In the previous post we saw how to inject a collection of values. However Spring is not limited to only wiring primitive values . It allows us to create collections of beans and wire them into other beans as well.

Sunday, 4 March 2012

Spring allows us to create beans that are wired with Collections and Arrays. In this post we shall create a simple class that has different collection based properties and then wire them with simple string values.

Saturday, 3 March 2012

Simply creating beans is not the only work of the container. We also need it to able to configure the newly instantiated beans. We need to 'inject dependencies' into these beans. There are two ways to inject the bean properties. One is using

Tuesday, 28 February 2012

In the previous example we saw how to set bean properties via the configuration. We can inject any value (or reference) into any property of the bean using the configuration files. However this leads to the side effect that the same bean reference may end up as a property among multiple beans.

In our previous posts we created an XML based configuration file that provided the Bean Factory information on the beans to be created. The XmlBeanFactory class takes a resource instance as a part of its constructor parameter.

Thursday, 23 February 2012

As we saw earlier the Persistence Cache holds a collection of loaded persistent objects. For every object that we load in Hibernate a separate copy (called a snapshot) is maintained within the persistence cache. This copy is used by Hibernate to mange dirty checks.(It is also used as a first level cache.) A downside to this phenomenon is that if we load a very huge object graph into the session there is a possibility that we might run into an OutOfMemoryException.

Tuesday, 21 February 2012

Calling session.save(entity) in the code does not cause an immediate SQL insert to be fired. Similarly session.delete(entity) or session.update(entity) will not result immediately in the execution of the sql delete or update queries being fired.When objects associated with the persistence context are modified, the changes are not immediately propagated to the database.

Sunday, 19 February 2012

As we saw earlier, with every hibernate session, a persistence context is associated. This context is aware of all the persistent objects that are associated with the hibernate session. The objects are maintained in maps with the identifier as the primary key. Hibernate very smartly uses this data to perform some query optimization.

Tuesday, 14 February 2012

The Hibernate framework is used to mange the persistence of objects. It allows objects to be associated with data present in the tables. It saves/modifies and inserts records in the database tables based on values in these objects and the operations performed on them using the Hibernate interfaces.
In the sequence of these operation calls, the data objects exist in various states. These states and the transition from one state to another forms the persistence life cycle.

In the previous post we saw how to create additional SQL using the <database-object> element. The queries were specified in the mapping file and Hibernate picked it from there and executed them as a part of the hbm2ddl operation.However Hibernate also allows us to programmatically control the generation of scripts.

Thursday, 9 February 2012

Hibernate's DDL export tool allows us to generate the SQL from our hbm mappings. However it is possible that we need to execute some additional sql that cannot be generated from the Hibernate mapping files. One way to do is by using the import.sql file. We can add all our triggers/procedures and other sql objects in this file and manage this file. Hibernate will execute this file as part of the database creation process.The other method is to create auxiliary database objects.

Tuesday, 7 February 2012

In the previous post we saw Spring and its relation to the term Beans. Now to look at beans from the implementation perspective. The first question is how to identify a Bean?
Beans in the xml file can be identified by their name or id property. For this post and a few others we shall use the below interface:

Monday, 6 February 2012

The definition of a database index from wikipedia is as follows:A database index is a data structure that improves the speed of data retrieval operations on a database table at the cost of slower writes and increased storage space.

Saturday, 4 February 2012

Whenever I come across the word Spring, the word bean is inevitably around the corner. Is there are any strong relation between the two ? Is it a part of Java glossary ? Or is it just a terminology bandied about by the Spring team. What exactly is this bean ?

I have been learning Hibernate ( and creating small examples) for quite some time now. And I am feeling a bit bored of this db thing now. I guess I need a change. So I decided to sharpen my skills at one another technology I have been using in the past year. Spring.
I have been using Spring in my project for the last year now. We started fresh on it with zero ground knowledge. At every stage of the development we have been amazed and impressed with what Spring has had to offer. So to bring a dash of change to the blog, I decided to take a stab at spring.
For my learning I had referred to a host of similar blogs, the Spring source site, my fellow workers, spring's source code and the book "Spring In Action- Second Edition". My knowledge might very well turn out to be a mix. (its definitely not something new, that I am putting out there ;) )Hope it helps.
This does not mean that Hibernate stops here. I shall continue with both Spring and Hibernate and at some point blog on a mix of the two. Till then cheers.

Friday, 3 February 2012

In earlier posts we saw how to use the hibernate hbm2ddl tool. We were able to create column constraints set unique column constraints and add not-null checks. In addition to those we saw before, Hibernate also allows creation of table level constraints such as foreign keys.

Monday, 16 January 2012

In the previous post, we saw how to create custom queries for Entity updating, insertion and deletion.Hibernate allows the use of both SQL procedures and functions to perform the Create/Delete and Update operations. I used the same entity class (Item) but instead of using the auto-increment property, I used the assigned generator. The reason for the change was issues faced in getting the insert procedure to work with auto-increment value. Hibernate needs this value which it is the result of the session.save method.

Monday, 9 January 2012

At start up Hibernate generates standard CRUD queries for each Entity that is mapped in Hibernate. However just like custom loaders, Hibernate provides with the option of using our own custom queries for the Create, Update and Delete (CUD) Operations

At its basic level Hibernate deals with SQL. All the fancy methods and HQL strings that we write end up being converted into the SQL that is understood by the database. Hibernate generates the appropriate SQL best suited for the Database provider we are using based on the dialect we have set in our hibernate configuration file.

<propertyname="dialect">org.hibernate.dialect.MySQLDialect</property>

There is a very rare probability that we may find the SQL queries generated unsuitable for our use. In such cases Hibernate comes with the option of overriding these queries with our own SQL queries.

Tuesday, 3 January 2012

Usually a foreign key references a Primary Key. However it is possible to have an extreme scenario wherein the foreign key refers a unique column in another table. To illustrate the above case let us create a simple(but highly contrived) example.

About Me

I am currently pursuing my masters in Computer Science at the University Of Texas at Dallas. Back in India I worked as a software engineer in the area of Java/J2EE for over five years. My experience is primarily in the financial and enterprise domain. I like tinkering around with the tools of my work and sharing the knowledge gained.