Friday, April 15, 2011

Lifecycle Callback Methods in JPA

JPA contains different lifecycle methods for monitoring changes in the the lifecycle of persistent objects. Every event in JPA has a corresponding callback method marker. These markers are shared between callback methods and their listeners. In JPA, these markers can be used for creating methods for callbacks by annoatating that method with callback annoatations. The lifecycle method annoations in JPA are: @PrePersist , @PostPersist, @PreUpdate, @PostUpdate, @PreRemove , @PostRemove and @PostLoad

Following are the rules that apply to lifecycle callback methods in JPA:
  • Methods can have public, private, protected, or package-level access, but must not be static or final.
  • A method may be annotated with multiple life-cycle event annotations. However, only one life-cycle annotation of a given type may be present in an entity class (you can’t have two @PrePersist annotations in the same entity, for example).
  • A method can throw unchecked (runtime) exceptions but not checked exceptions. Throwing a runtime exception will roll back the transaction if one exists.
  • A method can invoke JNDI, JDBC, JMS, and EJBs but cannot invoke any EntityManager or Query operations.
  • With inheritance, if a method is specified on the superclass, it will get invoked before the method on the child class.
  • If event cascading is used in the relationships, the callback method will also get called in a cascaded way. For example, let’s say a Student has a collection of addresses, and a cascade remove is set on the relation. When you delete the student, the Address @PreRemove method would be invoked as well as the Customer @PreRemove method.

Thursday, April 14, 2011

JPA Performance Benchmark(JPAB)

JPAB is a comprehensive benchmark that compares the performance of different combinations of JPA providers and Database Management Systems (DBMS). It covers many JPA ORM providers (Hibernate, EclipseLink, OpenJPA and DataNucleus) and DBMS (MySQL, PostgreSQL, Derby, HSQLDB, H2, HSQLite) that are available in Java.

It is recommended to check the following benchmark site while deciding the JPA ORM Providers for your project:

Java Double Brace Initialization

This is one of the hidden feature of Java. First of all, lets see some sample code:
ArrayList<String> tags = new ArrayList<String>() {{
Notice that there are two concurrent curly braces in the code. First brace creates an anonymous inner class and second brace is an instance initializer block that is run while anonymous inner class is instantiated.

Actually, it is just a rewrite of:
ArrayList<String> tags = new ArrayList<String>() {
// Initialization Block
The inner class created will be having a reference of its enclosing outer class and hence will use "this" pointer to add the string values in the tags arraylist.

So on running the following code:
System.out.println("First Tag: "+tags.get(0));
it will print:
First Tag: abc

Wednesday, April 13, 2011

"Configuration by Exception" Mechanism

Java EE 5 introduced the idea of configuration by exception (sometimes referred to as programming by exception or convention over configuration). This means, unless specified differently, the container or provider should apply the default rules. In other words, having to supply a configuration is the exception to the rule. This allows you to write the minimum amount of code to get your application running, relying on the container and provider defaults.

This concept is commonly used in JPA(Java Persistence API) where the mapping rules are specified as annotations. If you do not specify these rules, the classes will behave as simple POJOs.

Consider the following example:


public class Student {


private Long id;

private String name;

private Float rollno;

public Student()



….. // setters and getters


If you do not provide @Entity and @Id annotations, still Student will behave like a POJO and not be persisted.

Tuesday, April 12, 2011

Oracle Connection Process

To connect to a database service, clients use a connect descriptor that provides the location of the database and the name of the database service. Connect descriptor is a specially formatted description of the destination for a network connection and is usually described in tnsnames.ora.

Assume you have the following connect descriptor in your tnsnames.ora:
orcl =
(ADDRESS = (PROTOCOL = TCP)(HOST = myhost)(PORT = 1521))
Now, when you issue a connect, say like this:

$> sqlplus scott/tiger@orcl

tns will look in your tnsnames.ora for an entry called 'orcl'. Finding it, tns sends a request through the normal network stack to (PORT = 1521) on (HOST = myhost) using (PROTOCOL = TCP), asking for a connection to (SERVICE_NAME = orcl).

What happens behind the scene?

The database server receives an initial connection from a client application through the listener. The listener brokers client requests, handing off the requests to the Oracle database server. Every time a client requests a network session with a database server, a listener receives the initial request.

Each listener is configured with one or more protocol addresses that specify its listening endpoints. Clients configured with one of these protocol addresses can send connection requests to the listener.

Once a client request has reached the listener, the listener selects an appropriate service handler to service the client's request and forwards the client's request to it. The listener determines if a database service and its service handlers are available through service registration. During service registration, the PMON process—an instance background process—provides the listener with information about the following:
  • Names of the database services provided by the database

  • Name of the instance associated with the services and its current and maximum load

  • Service handlers (dispatchers and dedicated servers) available for the instance, including their type, protocol addresses, and current and maximum load
Depending on the type of handler selected, the communication protocol used, and the operating system of the database server, the listener performs one of the following actions:
  • Hands the connect request directly off to a dispatcher.
  • Sends a redirect message back to the client with the location of the dispatcher or dedicated server process. The client then connects directly to the dispatcher or dedicated server process.
  • Spawns a dedicated server process and passes the client connection to the dedicated server process.
Once the listener has completed the connection operation for the client, the client communicates with the Oracle database server without the listener's involvement. The listener resumes listening for incoming network sessions.

Friday, April 8, 2011

Sample Spring Configuration File in Spring 3.0

When building large enterprise applications, developer usually ends up with a lot of spring beans configured into Spring ApplicationContext. ApplicationContext allows us to interact with the configured beans.

Following is an example of basic 3.0 spring configuration file:

Spring provides extensive support for namespaces. In the above example, bean namespace is used for defining all basic definitions of the application and context namespace is provided for convenience for configuring core beans.

The property-placeholder will automatically locate and parse any property files you have in your classpath under the META-INF/spring directory.

The context:component-scan declaration will cause Spring to locate every @Component, @Repository, and @Service in your application. This allows you to write a POJO, and then simply annotate the new POJO as a @Service. Spring will then automatically detect, instantiate, and dependency inject your service at startup time.
The exclude-filter is declared to avoid instantiating our @Controller classes, as these should be instantiated by a web tier application context. 
Imports allow you to specify an external Spring configuration file to be integrated into your application context.

Patterns Used in Spring's Persistence Layer

The application tier that deals with persistence is often called the persistence tier. Spring helps to enforce a modular architecture in which the persistence tier is divided into several core layers that contain the following:

  • The Domain Model
  • The Data Access Object (DAO) Layer
  • The Service Layer (or Service Fa├žade)

Spring goes a long way towards reducing code complexity and maintenance. Following are mostly used of the patterns in spring’s persistence layer:

  1. Template Pattern: The Template pattern allows a template to be defined in which a series of standard steps are followed, delegating to a subclass for those operations that are specific to the business logic. For example, when working with Hibernate, it is first necessary to create and initialize a new Hibernate session and optionally begin a transaction, before executing any Hibernate operations. When the operations are completed, it is necessary to close the session, and optionally commit or rollback the transaction. It would be rather redundant to repeat these same steps each time it was necessary to interface with Hibernate. Instead, we can leverage Spring's HibernateTemplate or JpaTemplate abstractions, which handle these steps for us.
  2. Active-Record Pattern: In this pattern, an instance of a particular domain class represents a single row within the respective database table. To save changes to the instance (and thereby the appropriate row within the database), a save instance method is called directly on the instance. To delete an instance, we can simply invoke delete() on the instance that needs to be deleted. Query operations are usually invoked as static methods on the domain class itself.

Folder Structure for a Standard Maven 3 Web App

Taken from Chapter 3 - Basic Application Setup

Spring Persistence with Hibernate

Though you can define a custom directory structure and modify your Maven settings or graft Maven onto a legacy project with a directory structure that's already defined, your best bet is to stick with the basic folder structure that Maven expects. That will ensure proper interoperability with all of the plugins and tools that are available.

To build a basic art gallery application, start by making a folder called gallery:

mkdir gallery

Within the gallery folder, create the folders that are customary for a Java application:

mkdir gallery/src mkdir gallery/src/main mkdir gallery/src/main/java mkdir gallery/src/main/resources mkdir gallery/src/main/resources/META-INF 

For web applications, we need a webapp and WEB-INF folder:

mkdir gallery/src/main/webapp mkdir gallery/src/main/webapp/WEB-INF 

We also need to create the folders that are required for unit testing our application:

mkdir gallery/src/test mkdir gallery/src/test/java mkdir gallery/src/test/resources 

And finally, create the two folders where Spring configuration files are ordinarily placed:

mkdir gallery/src/main/webapp/WEB-INF/spring

mkdir gallery/src/main/resources/META-INF/spring

You can also have maven automatically generate your project's structure by using Maven's archetype feature. Maven archetypes are like project templates that can be used to streamline the creation of a maven project, including setting up your directory structure and a baseline pom.xml file.