Search This Blog

Friday, 28 December 2012

Criterion

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

Criteria API - the basics

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

HQL and Nested Queries

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.

Thursday, 20 December 2012

SOAP Webservices using Spring -3

As of now we have configured the web service and have also made our contract (or WSDL ) visible to the client. But what happens when the client actually sends a request? How do we handle it?

Wednesday, 19 December 2012

SOAP Webservices using Spring -2

In the previous example we saw how to set up the application and add the WSDL and XSD files needed. We also configured a MessageDispatcherServlet to handle the operations exposed by our web-service.

Tuesday, 18 December 2012

SOAP Webservices using Spring -1

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) .

Saturday, 15 December 2012

HQL and Dynamic Fetching strategies

We saw in our earlier post that HQL ignores the fetching strategy in our mapping. Consider the below query which fetches an entity with id 1.
public static void testNormalFetch() {
    final Session session = sessionFactory.openSession();

Wednesday, 12 December 2012

Handling exceptions in Spring MVC

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

The Fetch Plan and the Fetch Strategy.

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

Group by and having clauses in HQL

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

HQL and aggregrate functions

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:

Tuesday, 4 December 2012

Reading the date in the request parameter

In the previous posts we saw how Spring allows us to accept request parameters as method level parameters for our Controllers. This is all very easy when we are dealing with String parameters like "first name " or "address". But what if we have date of birth?

Sunday, 2 December 2012

The ResourceLoaderAware Interface

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.

Friday, 30 November 2012

Upload and Download files- continued

In the previous post we saw how to process the MultipartFile parameter. We then wrote code to convert it into a byte array and use it in our code. This all works fine.
However we have seen custom editors that are capable of converting string parameters in HttpServletRequest into objects

Thursday, 29 November 2012

Upload and Download files

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

Resource Loading in Spring

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.

Processing Parameters in Spring

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

Replicating Records Across Tables

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.

Saturday, 24 November 2012

Springs' ContextLoaderListener

In an earlier example we show how to load beans from multiple configuration files. This is mostly needed in web applications where we write the different bean definitions in different layers.

Friday, 23 November 2012

Importing from other configuration files

One of the best practises we follow in Application development is modularity. Separation of concern is an important design practise that can also be applied to our XML configuration.

Monday, 19 November 2012

gzip your Tomcat response

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

The Hibernate Inheritance Mechanism - Flashback

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.

Thursday, 15 November 2012

Using annotation based handler mappings

In earlier posts we saw the different URL handler mappings available to enable the servlet to route requests to correct controllers. Spring has also introduced annotation based controllers.

Tuesday, 13 November 2012

Using Multiple URL Handler Mappings

As we saw earlier Spring supports a variety of URL handler mappings. In fact we can use multiple URL Handler mappings in the same application.

Sunday, 11 November 2012

Forcefully initializing proxies in Hibernate

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, 9 November 2012

Spring MVC without URL Mappings ?

In an earlier example we saw that Spring uses a single front-controller servlet. The Servlet then delegates the request to the controllers. This was achieved by mapping the controllers to urls.

Tuesday, 6 November 2012

The ModelAndView

In our previous example we did not explore the ModelAndView object in detail. We simply passed the control to a static jsp page. I modified the example to deal with a jsp with some dynamic content.

Sunday, 4 November 2012

Basic MVC application in Spring

Spring provides support for MVC based web application development. I decided to create a very basic application involving a simple HTML page and a JSP page.

Friday, 2 November 2012

Eager fetching does not work for parallel bags

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

Formatting code using Eclipse

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" ?

Tuesday, 30 October 2012

The wrong result when using fetch and DISTINCT keywords

Consider a query to fetch all entities who have a child with id 1.
public static void testQuerySingleE() {
    final Session session = sessionFactory.openSession();  
    Transaction transaction = session.beginTransaction();

Saturday, 27 October 2012

HQL and the new keyword

It often happens that for a particular use case we need columns from several different tables. Consider the case where we would like the Entity name and its Master Name to be displayed.

Thursday, 25 October 2012

Theta Style Joins

Consider the below queries to find all children of an entity:
public static void testGetEntityChild() {
    final Session session = sessionFactory.openSession();

Wednesday, 24 October 2012

Querying and Outer Joins

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

Quering and Inner joins

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.

Wednesday, 17 October 2012

HQL functions - more of them

In the previous post we saw some common HQL functions. I decided to explore them some more.

Tuesday, 16 October 2012

HQL functions

HQL has the ability to use functions in the WHERE clause.There are the JPA defined functions and also additional HQL functions available for use:

Sunday, 14 October 2012

HQL - The where clause - 2

Continuing from the previous post, I decided to try out other HQL queries

Thursday, 11 October 2012

Attributes in Spring's @Transactional Annotation

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

Caching binary content coming from databases

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.

Spring's @Transactional annotation

Up till now we have seen various ways to achieve transactional behavior in Spring. We saw
Now to do things the easiest way - using annotations.
Since version 2.0 Spring came up with annotations to manage declarative transactions. I decided to use JDBC to test out the annotations.

Friday, 5 October 2012

Programattic Transactions

In the previous post we saw how Spring allows us to use advices for transaction management. However Spring also provides support for programatically managing transactions.

Thursday, 4 October 2012

tx:advise

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

Managing Transactions the Spring way 2

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

Managing Transactions the Spring way

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.

Thursday, 27 September 2012

Caching in Spring-2

In our previous post we saw how to use Spring and  Ehcache. We did that through a lot of XML configuration. Spring also provides us with annotations to use.

Tuesday, 25 September 2012

Caching in Spring

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

Managing module dependency versions with Maven

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.

Friday, 21 September 2012

Spring and Hibernate 2

In the previous post we saw the working of the HibernateTemplate. As discussed Spring doesn't need us to work with it. We can now directly work with the SessionFactory.

Thursday, 20 September 2012

Spring and Hibernate

In our earlier post we saw how Spring can be integrated with JDBC. Spring also provides a similar template class for use with Hibernate - org.springframework.orm.hibernate3.HibernateTemplate.

Wednesday, 19 September 2012

String Pool and SLF4J

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.

Saturday, 15 September 2012

HQL - The where clause

Logic in applications almost always involves execution of queries involving where clauses on the database. HQL also supports where clauses.

Friday, 14 September 2012

HQL - Getting all the records in the database

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.

Tuesday, 11 September 2012

Spring JDBC and SqlUpdate

In the previous posts we used the JDBC template's update() method to insert, update and delete data.There is another technique available if we do not want to work with the template.

Monday, 10 September 2012

Friday, 7 September 2012

Spring JDBC and SqlQuery

In an earlier post we saw how to use the JdbcTemplate to retrieve multiple rows from the database. There is an alternative way to do the same - using the org.springframework.jdbc.object.SqlQuery class.

Wednesday, 5 September 2012

Spring JDBC and the SqlFunction

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:

Tuesday, 4 September 2012

HQL and aliases

In the previous post we saw how query execution works in Hibernate and we created a simple relationship that we could use to test our different HQL queries.

Saturday, 1 September 2012

Querying with HQL - the basics

Hibernate provides us with its own query language - HQL or Hibernate Query Language. To understand the same I created a simple Entity class:

Thursday, 30 August 2012

Spring and JDBC

I decided to implement the IPersonDAO interface to work with JDBC.
public class SimplePersonDAO extends SimpleJdbcDaoSupport implements IPersonDAO {
    private static final Logger logger = Logger.getLogger(PersonDAO.class);
//remaining methods
}

Wednesday, 29 August 2012

Spring and Database - the cool stuff - 2

In the previous post we saw that Spring gave us a generic way to handle Data access exceptions. The next goodie from the Spring box is the ability to ignore the database access code and focus on the actual database logic.

Sunday, 26 August 2012

Spring and Database - the cool stuff

Spring gives us some real cool advantages when integrating with databases. Theses advantages are applicable whether you connect to the database via JDBC or via frameworks.

Friday, 24 August 2012

Spring And The Actual DB Operations

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.

Thursday, 23 August 2012

Pooled Data-sources and Spring -2

In the previous post we saw how Spring integrated with DBCP. There is another data-source c3p0 which can also be integrated via Spring.

Monday, 20 August 2012

Pooled Data-sources and Spring

In an earlier post we saw non pooled data-sources. However both DriverManagerDataSource and SingleConnectionDataSource have their own limitations.

Saturday, 18 August 2012

Managing Data-sources via Spring

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. 
The article found in Java blog also covers the concept very well.

Thursday, 16 August 2012

fetch = join and the Cartesian Product Problem

When we apply the join fetch strategy, the data is fetched using joins. We saw this for collections and associations.This leads to a problem when there are multiple collections in the same entity.

Tuesday, 14 August 2012

fetch = join for non-Collection Association

In the previous post we applied the join fetch strategy for collections. Now I shall apply them to a many-to-one and a one-to-one association.

Sunday, 12 August 2012

Property files and @Value

In the previous post we saw how property file values could be used to configure our beans in the XML files. Spring has also come up with annotations to allows us to configure our bean's properties via code:

Saturday, 11 August 2012

Using Spring's property-placeholder

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

Publishing Events asynchronously

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

fetch = join for Collection

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

fetch = subselect

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

batch-size =n

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

The N +1 Select Problem in Hibernate

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.

Friday, 27 July 2012

Using Interception in Hibernate -2

To continue from where we left our previous discussion, byte code interception is mainly used when we need to lazily load some of our properties.

Wednesday, 25 July 2012

Using Interception in Hibernate -1

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

lazy="extra"

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

Are Interceptors Thread Safe ?

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

Logging using Interceptors

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

Testing the Interceptor

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 and Events and Listeners

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

Hibernate Queries and the Question Mark

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

Listeners in Hibernate

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.

Sunday, 8 July 2012

The MessageSourceAware Interface

While we can use the ApplicationContext for Internationalization, we may also need the functionality to be available to normal beans.

Thursday, 5 July 2012

Reloadable MessageSources

As we saw in the previous post, the ResourceBundleMessageSource uses underlying JDK's ResourceBundle implementation. The java.util.ResourceBundle loads locale specific files or bundles only once. It caches loaded bundles forever: Reloading a bundle during program execution is not possible. As this MessageSource relies on ResourceBundle, it faces the same limitation.So we are stuck with the same set of values. Spring provides us with an alternative implementation - ReloadableResourceBundleMessageSource.

Tuesday, 3 July 2012

Spring and Message Loading

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.

Sunday, 1 July 2012

Lazily loading beans ?

One of the differences between BeanFactory and ApplicationContext is their method of loading beans. The beanfactory lazily loads beans. It creates the bean only when the getBean() method is called.

Saturday, 30 June 2012

Intercepting Events in Hibernate

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

Data Filters in Hibernate

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

Stateless Session

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.

Friday, 22 June 2012

Hibernate And Bulk Operations -2

I the previous post we saw bulk updates via Hibernate. We can also perform bulk deletes and bulk inserts through Hibernate.
Bulk Deletes
static void testBulkDelete() {
    Session session = sessionFactory.openSession();
    Transaction transaction = null;

Tuesday, 5 June 2012

Hibernate And Bulk Operations -1

We have often executed SQL queries of the type:
update <table> set <record_column> = <value> where <condition>;
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

Hibernate And Batch Operations

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, 13 May 2012

The ApplicationContextAware Interface

In the previous post we saw how the ApplicationContext as the more powerful container in Spring. In a BeanFactory based environment Spring provides us with the BeanFactoryAware interface to help a bean get access to its loading BeanFactory container.Similarly for the application context

Tuesday, 1 May 2012

Using the ApplicationContext

In all of the previous posts we have been working with the BeanFactory. However in order to use all of Spring's functionalities we need to use a more powerful version of the Spring Container.

Sunday, 29 April 2012

Bean Creation via Factory Method

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.

Thursday, 26 April 2012

Using BeanPostProcessors

Spring provides us with BeanPostProcessor classes that can be used to process beans before and after they have been configured by the container.

Tuesday, 24 April 2012

Creating default init and destroy methods

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

The InitializingBean and DisposableBean Interfaces

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

Custom Bean Initialization and Destroy Methods

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

BeanNameAware and BeanFactoryAware

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.

Monday, 16 April 2012

The Bean Lifecycle

I was studying the life cycle of the bean in a Spring application. The Spring container performs several step in the bean creation process before making it available to the use for the application.

Saturday, 14 April 2012

The autowire-candidate attribue

There may arise a scenario wherein we do not want certain beans to be autowired into the property of other beans. Consider the Simple Car class from an earlier example:

Thursday, 12 April 2012

The default-autowire attribute

We have seen that Spring supports a variety of auto-wiring options. Spring Container allows us to set a default autowiring for all the beans.

Wednesday, 11 April 2012

Can we auto and explicitly wire a bean ?

While the Spring Container allows us to auto-wire a bean, it does not mean, that the bean must be completely auto wired by the container.

Tuesday, 10 April 2012

Autodetecting The Autowiring

The last technique in autowiring is auto-detect. In this case we tell the Spring container to uses its own brains while configuring the bean.

Saturday, 7 April 2012

One to One and Proxies

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

Lazy Behavior in Hibernate

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.)

Sunday, 1 April 2012

hibernate.use_identifier_rollback

Consider the below code that loads an entity from the database and deletes it.
public static void rollBackDelete() {
    Session session = sessionFactory.openSession();
    Entity entity = new Entity(); 

Saturday, 31 March 2012

Merging A Detached Object

In an earlier post we saw how to reattach detached objects using update() and lock(). Consider the below code where we try to reattach an object.
public static  void needForMerge() {

Saturday, 24 March 2012

get() versus load() - Things Get Murkier

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

get() versus load()

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

From Detached to Removed

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 :

Saturday, 17 March 2012

Autowiring By Constructor

In this technique, the Spring Container tries to match up beans in the container with the parameters of the constructor arg while creating the bean. Consider the CarByConstructor class:

Autowiring By Type

In this type of autowiring the Spring Container will attempt to configure the bean properties based on the type of the property. Consider the below ICar implementation:

Sunday, 11 March 2012

Autowiring - By Name

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

Injecting Null

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

Injecting Collections of Objects

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

Injecting Value Based Collections

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

Injecting Properties Of Beans

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

Thursday, 1 March 2012

The p namespace

<bean id ="band" class ="com.performer.Band">
    <property name="musician" ref="musician"></property>
    <property name="singer" ref="singer"></property>
</bean>
The above XML fragment

Tuesday, 28 February 2012

I don't want to share my bean

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.

Loading the Configuration

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.

Saturday, 25 February 2012

Making A Detached Object Persistent Again

Hibernate allows detached objects to be associated with a persistence context again.One way to achieve this is to use the update method of the session.

Thursday, 23 February 2012

Controlling the size of the Persistence cache

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

Write-Behind Technique In Hibernate

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

First Level Cache and Repeatable Reads

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.

Friday, 17 February 2012

Automatic Dirty Checking

Consider the below code which loads a simple Entity from the database and updates it.
public static void testUpdate() {
    Session session = sessionFactory.openSession();
    Transaction transaction = session.beginTransaction();

Thursday, 16 February 2012

The Hibernate Persistence Context

In our previous post we saw the object cycle and how the Hibernate session kept a tab on all the persistent objects. A call to session.toString() returns the following:
SessionImpl(PersistenceContext[entityKeys=[EntityKey[com.mode
l.Entity#1]],collectionKeys=[]];ActionQueue[insertions=[] updates=[] deletions=[
] collectionCreations=[] collectionRemovals=[] collectionUpdates=[]])
There is something inside the Hibernate session called the PersistenceContext. What is it ?

Tuesday, 14 February 2012

The Hibernate Object Life-Cycle

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.

Sunday, 12 February 2012

To Singleton or Not To Singleton

Consider the below bean definition in our spring configuration file
<bean id="pBean" class="com.performer.Singer"/>

AbstractAuxiliaryDatabaseObject

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

Auxiliary database objects

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

Identifying Beans - Name or Id

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

Creating sql indexes via Hibernate

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

Spring and Beans

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 ?

The Spring Container

In our previous post we saw how the BeanFactory was used. If the same code was to be written without spring

A Simple Spring Program

In this post, I shall attempt to create a simple bean using spring.
Task:

Sharp Turn in the Road

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

Creating Column, Table and Database level constraints

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

Insert,Update,Delete via Procedures and Functions

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

Creating Custom Insert,Update,Delete Queries

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

Creating Custom Entity Loaders

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.
<property name="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.

Sunday, 8 January 2012

Composite Foreign Key referencing Nonprimary Keys

In the previous post we had a scenario wherein the foreign key was not actually referring to the primary key but instead to another natural key. Let us take this not -so normal scenario a step further into the weird. What if the natural key is formed by a group of columns as opposed to the single column natural key we saw earlier ?

Tuesday, 3 January 2012

Foreign Key referencing Nonprimary Keys

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.

Sunday, 1 January 2012

Compisite Identifiers And Associations-2

Continuing from the previous post, if Student were to have a many-to-one association with Books, then the foreign-key(user_name) would also be present in this association.