Plain Old Java Object (POJO)

POJO is YAA (yet another acronym) for Plain Old Java Object, and is favoured by advocates of the idea that the simpler the design, the better. Nowadays POJO’s are everywhere. The name was coined by Martin Fowler, Rebecca Parsons and Josh MacKenzie in September 2000. Most of our development today is done using POJOs.

In Chris Richardson’s (author) words -

The simplicity of POJOs is attractive, especially to those working with the older Enterprise Java Beans (EJB) specification. The topic assumes a simple axiom: The simpler a framework’s design, the more extensible it is to programmers. For example, in an open letter to the Java community, Linda DeMichiel and Craig Russell talk briefly about adopting POJOs for both Java Data Objects (JDO) API 2.0 and the new EJB 3.0 specification, pronouncing the need for a single, simple persistence model. As the FAQ notes, this API “is an evolution of the work started in the JSR 220 Expert Group, which has been expanded to include several members of the JSR 243 (JDO 2.0) Expert Group.” JSR 220 covers the creation of the EJB 3.0 specification, with a stated mandate “to improve the EJB architecture by reducing its complexity from the developer’s point of view.”

The term continues the pattern of older terms for technologies that do not use fancy new features, such as POTS (Plain Old Telephone Service) in telephony, and PODS (Plain Old Data Structures) that are defined in C++ but use only C language features.

The term has most likely gained widespread acceptance because of the need for a common and easily understood term that contrasts with complicated object frameworks. A JavaBean is a POJO that is serializable, has a no-argument constructor, and allows access to properties using getter and setter methods. An Enterprise JavaBean is not a single class but an entire component model (again, EJB 3 reduces the complexity of Enterprise JavaBeans).

The concept of a POJO predates the term POJO as it simply refers to the natural condition of an object class. The term serves as a reminder that simpler designs can be better, rather than incorporating a complicated framework in the architecture of a system without sufficient reason. As designs using POJOs have become more commonly-used, systems have arisen that give POJOs some of the functionality used in frameworks and more choice about which areas of functionality are actually needed. Hibernate and Spring are examples.

The Seven Relationship Types.

Seven types of relationships can exist between entity beans. There are four types of cardinality: one-to-one, one-to-many, many-to-one, and many-to-many. In addition, each relationship can be either unidirectional or bidirectional. These options seem to yield eight possibilities, but if you think about it, you’ll realize that one-to-many and many-to-one bidirectional relationships are actually the same thing. Thus, there are only seven distinct relationship types.

To understand relationships, it helps to think about some simple examples:

One-to-one unidirectional

One-to-one bidirectional

One-to-many unidirectional

One-to-many bidirectional

Many-to-one unidirectional

Many-to-many unidirectional

Many-to-many bidirectional

Note that these relations represent the navigability of your domain model.

Once again, the associations defined in the metadata represent the domain object navigation only.

Features and Advantages of JPA:

Java Persistence API is the standard API used for the management of the persistent data and object/relational mapping.

Java Persistence API were added in Java EE 5 platform.

Every application server compatible with Java EE 5 supports the Java Persistent APIs.
Java Persistence API ensures the management of persistence and object/relational mapping.

These are helpful while using the JPA in the development of applications using the platform for Java EE 5. It provides O-R mapping facility to manage relational data in java application.

The Java Persistence API contains the following areas:

Java Persistence API
O-R mapping metadata
The query language

Java Persistence API is a lightweight framework based on POJO for object-relational mapping. Java language metadata annotations and/or XML deployment descriptor is used for the mapping between Java objects and a relational database. It allows the SQL-like query language that works for both static as well as dynamic queries. It also allows the use of the pluggable persistence API. Java Persistence APIs are mainly depends on metadata annotations.

API includes:

Java Persistence API
Metadata annotations
Java Persistence query language

The Java Persistence API is build upon the best ideas from the persistence technologies like TopLink, JDO and Hibernate. Java Persistence API is compatible with Java SE environment as well as Java EE and allows developers to take advantages of the standard persistence API.

Persistence of data is not so easy for most of the enterprise applications because for this they require access to the relational database like Oracle 10g. It is your responsibility to update and retrieve the database by writing the code using SQL and JDBC.

While several object-relational (O-R) frameworks such as JBoss Hibernate and OracleTopLink make persistence challenges simpler and became popular. They let the java developer free from writing JDBC code and to concentrate only on the business logic.

In EJB 2.x, container manage persistence (CMP) try to solve the persistence challenges but not successful completely.

Annotations

Annotation is the method of associating the program elements with the meta tags so that the compiler can extract program behavior to support the annotated elements to generate interdependent code when necessary.

The objective behind annotations is to make the development (“i.e. coding”)  process easier.

Annotations behaves like the meta. The literal meaning of meta data is data about data. Java also signifies this meaning. Annotations are like meta data, means you are free to add your code and can also apply them to variables, parameters, fields type declarations, methods and constructors.

Metadata is also used to create the documentation to perform rudimentary compile time checking and even for tracking down the dependencies in code.

XDoclet contains all these features and is widely used.

Annotations provide a means of indicating about methods, classes, dependencies, incompleteness and also about the references on other methods and classes respectively. Quoting from Sun’s official site, “It (annotation-based development) lets us avoid writing boilerplate code under many circumstances by enabling tools to generate it from annotations in the source code. This leads to a declarative programming style where the programmer says what should be done and tools emit the code to do it.”

Dependency injection

Dependency injection is the mechanism through which the container injects the requested environmental entry to make available to the bean instance before any bean instance is invoked on that particular instance. Then the container injects these entries into bean variables or methods.

It is a form of push configuration; the container “pushes” dependencies into application objects at runtime. This is the opposite of traditional pull configuration, in which the application object “pulls” dependencies from its environment. Thus, Dependency Injection objects never load custom properties or go to a database to load configuration — the framework is wholly responsible for actually reading configuration.

Dependency Injection is based on Java language constructs, rather than the use of framework-specific interfaces. Instead of application code using framework APIs to resolve dependencies such as configuration parameters and collaborating objects, application classes expose their dependencies through methods or constructorsthat the framework can call with the appropriate values at runtime, based on configuration.

It is bean provider’s duty to tell the container that which method or variables should be injected at runtime. The bean provider can do this by using the deployment descriptor or annotations. Bean methods used for dependency injection should follow the java naming convention(JavaBeans) for properties in that they should follow the setXYZ() convention.

Consider the situations like dependency injection fails due to some reasons, the container can not make available the environmental entries due to which the bean is functioning properly, in such situations the container discards the bean instances and creates new instances.

EJB 3.0′s Concurrency Control.

Concurrency control is a necessary part of distributed systems it house’s the basics of collisions and type of collisions that can occur. The EJB Container provides supports for various types of concurrency controls. For now we will concentrate on collision and then techniques to resolve these collisions.

A collision can occur when two or more transactions tries to change the entities within a system of records. There are three causes which interfere:
Dirty read
Non Repeatable read
Phantom read

Mainly two mechanism are used to control the concurrency.
Optimistic Locking
Pessimistic Locking

Persistence and Entity Beans

Persistence is a higher-level abstraction above JDBC. The persistence layer maps objects to database storage so that they can be queried, loaded, updated, or removed without having to go through a verbose API such as JDBC. In older versions of EJB, persistence was part of the EJB platform. Starting with EJB 3.0, persistence has been spun off to its own specification, called the Java Persistence API.

The Java Persistence API defines a way to map regular, plain old Java objects (sometimes referred to as POJOs) to a database. These plain Java objects are called entity beans. Entity beans are like any other Java class, except that they have been mapped, using Java Persistence metadata, to a database. Therefore, they may be inserted and loaded from a database without the developer writing any JDBC connection code or reading from result sets. The Java Persistence API also defines a query language that has features that parallel those in SQL, but is tailored to work with Java objects rather than a raw relational schema.

In the EJB 2.1 specification, entity beans were very “heavyweight” and dependent on the application server and the entire Java EE runtime environment. In Java Persistence, entity beans are regular Java objects that are managed by a persistence service. Unlike their EJB 2.1 counterparts, entities in Java Persistence are not required to implement any special spec-defined interfaces or classes. Another weakness of the older specification was that it left individual vendors to decide how an object should be mapped to a particular database representation. This made EJB 2.1 entity beans mostly nonportable between vendors. The new Java Persistence specification defines a complete object to relational mapping (ORM) so that entity beans can be ported easily from vendor to vendor. Furthermore, because entity beans are now plain Java objects, they are not just portable between application servers; they can be used in regular Java applications outside of an application server and can even be used to transfer data between a client and a server. This makes designs simpler and more compact.

An Entity

An Entity defines an abstract type of object, the instances of which can be mapped into a relational table, ie a table containing a header consisting of a set of attributes, and a body consisting of a variable set of tuples (rows with values for the attributes).

Any concrete or abstract thing of interest, including associations among things; for example, a person, object, event, or process that is of interest in the context under consideration, and about which data may be stored in a database.

An Entity is something that has a distinct, separate existence, though it need not be a material existence. In particular, abstractions and legal fictions are usually regarded as entities. In general, there is also no presumption that an entity is animate.

it is useful for managing all the information about a client, during the whole lifetime of the client, ie it has to keep this information also between successive shutdowns and reboots of the system. So, it has a persistent state and a persistent identity, which are both visible to its clients.

An Entity is a thing of significance, either real or conceptual, about which the business or system being modeled needs to hold information. Sample entities: EMPLOYEE, DEPARTMENT, CAR, etc. Each entity in a ERD (Entity Relationship Diagrams) generally correspond to a physical table on database level.

Enterprise JavaBeans Technology (EJB 3.0)

Enterprise Java Beans is a component architecture for the development and deployment of object-oriented, distributed, enterprise-level applications. Applications written using the Enterprise JavaBeans architecture are scalable, transactional, multi-user and secure.
EJB is designed to support application portability and reusability across any vendor’s enterprise middleware services.

EJB is a standard for developing and deploying server-side distributed components in Java. It defines an agreement (contract) between components and application servers that enables any component to run in any compliant application server.

Despite the rich features, the complexity of the EJB architecture has hindered its wide adoption. Various component technologies have taken over the EJB arena. For example Toplink and the open-source Hibernate framework have overtaken EJB as a better and easier choice for developing persistence solutions.

EJB 3.0 brings us closer to the dream of creating enterprise beans like regular objects. It reduces the number of programming artifacts for developers, eliminates or minimizes callback methods required to be implemented, and reduces the complexity of the entity bean programming model and O/R mapping model. With EJB 3.0, J2EE now Java EE seems accessible to a much wider audience.

In this article, we first briefly discuss the pitfalls of EJB 2.1. Next, we describe how EJB 3.0 provides solution to these difficulties by describing the significant changes.

Pitfalls of EJB 2.1.

EJBs with EJB 2.1 hasn’t been the easiest thing to do. The reasons are easy to find:

  • To create a single EJB you need to create a multitude of XML deployment descriptors.
  • A set of three source files must be created.
  • Multiple callback methods must be implemented that usually are never used.
  • You have to throw and catch several types of unnecessary exceptions.
  • Yet another complaint is that the EJBs are completely untestable outside the context of the container since components like container-managed entity beans are abstract classes.
  • Finally, EJB-QL in its current form is limited in functionality and difficult to use. These limitations force developers to use straight JDBC and SQL, or to use other persistence frameworks such as Toplink and Hibernate.

The sheer verbosity of the API has been one big annoyance, and EJB 3.0 makes a significant attempt to address most issues. This article covers the important aspects of this specification.

The two most significant changes in the proposed EJB 3.0 specification are the use of the program annotation facility introduced in Java 5 and the new O/R mapping model based on Hibernate’s pattern.

Java SE 5 has introduced a new program annotation facility to the language. With this facility, you can define custom annotations and then annotate fields, methods, classes, etc., with these annotations. Annotations do not directly affect program semantics, but tools (compile time or runtime) can inspect these annotations to generate additional constructs (like a deployment descriptor) or enforce desired runtime behavior (like an EJB component’s stateful nature).

Annotations can be inspected through source parsing (e.g., compilers or IDE tools) or by using the additional reflection APIs added in Java 5. Annotations can be defined to be available only at the source code level, at the compiled class level, or at runtime. All annotations proposed in the EJB 3.0 early draft have a RetentionPolicy of RUNTIME.

This increases the class’s memory footprint marginally, but makes the life of container provider and tool provider much easier.This brings to an end the configuration of XML deployment descriptors was a major bottleneck in the path to simplifying development of EJBs. Therefore one of the primary goals of the EJB 3.0 specification was to shield the developer from having to work with XML files.

This is accomplished by the use of metadata annotations that have been added to JDK 5.0 as part of the JSR 175 JCP specification. Annotations are a kind of attribute-oriented programming and are similar to XDoclet.

However, unlike XDoclet, which requires pre-compilation, annotations are compiled into the classes by the Java compiler at compile-time. From the developer’s point of view, annotations are modifiers like public/private and can be used in classes, fields, or methods.

Hibernate is a popular, open source O/R mapping framework for Java environments, meant to shield developers from most common data-persistence-related programming tasks. It also has a specific Hibernate Query Language (HQL), imprints of which can be seen in the new EJB QL. Hibernate offers facilities for data retrieval and update, connection pooling, transaction management, declarative entity relationship management, and declarative and programmatic queries.

The new entity beans are also just POJOs with a few annotations and are not persistent entities by birth. An entity instance becomes persistent once it is associated with an EntityManager and becomes part of a persistence context. A persistence context is loosely synonymous with a transaction context; in strict words, it implicitly coexists with a transaction’s scope.

The entity relationships are also defined through annotations। In addition, O/R mapping is also done through annotations, and support for several database-specific operations is provided.

With EJB 2.1, developers used their own design patterns or employed nonportable techniques (for example, auto key generation strategies).

The main aim of the EJB 3.0 is to provide an improved EJB architecture by reducing its complexity from enterprise application developer’s point of view.

EJB 3.0 is focused on the following goals:

  • Definition of the Java language metadata annotations that can be used to annotate EJB applications. These metadata annotations are targeted at simplifying the developer’s task, at reducing the number of program classes and interfaces the developer is required to implement, and at eliminating the need for the developer to provide an EJB deployment descriptor.
  • Specification of programmatic defaults, including for metadata, to reduce the need for the
    developer to specify common, expected behaviors and requirements on the EJB container. A “configuration by exception” approach is taken whenever possible.
  • Encapsulation of environmental dependencies and JNDI access through the use of annotations,
    dependency injection mechanisms, and simple lookup mechanisms.
  • Simplification of the enterprise bean types.
  • Elimination of the requirement for EJB component interfaces for session beans. The required business interface for a session bean can be a plain Java interface rather than an EJBObject, EJBLocalObject, or java.rmi.Remote interface.
  • Elimination of the requirement for home interfaces for session beans.
  • Simplification of entity persistence through the Java Persistence API. Support for light-weight
    domain modeling, including inheritance and polymorphism.
  • Elimination of all required interfaces for persistent entities.
  • Specification of Java language metadata annotations and XML deployment descriptor elements for the object/relational mapping of persistent entities.
  • A query language for Java Persistence that is an extension to EJB QL, with addition of projection, explicit inner and outer join operations, bulk update and delete, subqueries, and
    group-by. Addition of a dynamic query capability and support for native SQL queries.
  • An interceptor facility for session beans and message-driven beans.
  • Reduction of the requirements for usage of checked exceptions.
  • Elimination of the requirement for the implementation of callback interfaces.