Archive for September, 2008

Google Phoenix Closing Doors

News out of Google says that on November 21, 2008 the Internet search giant’s office in Phoenix, Arizona will close its doors. This is not a reduction in the number of Google employees though there is a possibility that those who are not able to move out of Phoenix may choose to find other alternatives. However the closure underscores a shift that Google may be under taking as it increasingly need to cope with the fact that it is a more grown up venture thus optimizing its operations to ensure that it builds on its existing assets becomes imperative.

This particular story caught my interest because of the need to ensure entrepreneurial spirits in this day and age and nobody would disagree with the assertion that Google has done more to foster entrepreneurial spirit in its employees. They tend to attract people who have the potential to be intrapreneur and this is key to their on going success.

However the balance between maturing organization structure, policies and procedures on the one hand and instilling entrepreneurial spirit throughout the work force is a delicate one. I don’t know if current Google employees still do feel the start-up spirit at the search giant or they have become more comfortable with an increasingly well structured organization with policies and procedures for everything and the ensuing requirement to follow the laid down rules as it were.

Advertisements

Leave a comment

Simple Java Persistence API (JPA) Demo Part II

Overview

In this belated installment of the JPA demo series, I will complete what the first installment started. I will look at what happens beyond the basic entities that were defined in the first post. Fill in as much details as possible. Note that this is not meant to be an article gives you all the information that you need to know about JPA. Instead, I will restrict myself to what is relevant in a hands on examination of JPA; there are certainly much more exhaustive information on the subject on the web but we are going to look at appreciating JPA from a hands on perspective. Ok, enough of the reminder.

This installment of the series will dwell on the Entity manager mostly but also touch on any of the parts of JPA that are closely associated with the Entity manager such as Entity Manager Factory and Persistent Context and persistent Units. The post also includes a code sample that shows the creation of an entity manager in action.

The application used to show the concepts behind JPA has a simple structure that also tries to incorporate some aspects of good application design such as separation of concerns which allows the tiers/layers of the application to be as independent from each other as possible.

Entity Manager

Each entity in the domain model goes through a life cycle which typically defines its creation, persistence, retrieval, updates and finally removal. The Entity Manager interface provides methods to enable applications to manage the life cycle of objects in the domain model. You can think of the necessity of the Entity Manager from this perspective: if the Entity class, by its implementation, is not aware of the specifics of the database that will keep its data, then it is a good idea to have another API that will have some understanding of the persistence layer and perhaps even have it as an integral part of the persistence layer. The entity manager players an important role in the architecture of applications that use JPA for persistence.

All entity managers are created from an EntityManagerFactory class; the particular factory class from which an EntityManager is created determines the EntityManager’s configuration. You have the option of application managed (Java SE) EntityManager or Container managed (Java EE) EntityManager. In Java SE there is a bootstrapping class called Persistence that enables you to create an EntityManagerFactory class. However in a Java EE compliant application server you can have the server lookup a Persistent Unit to use in creating the EntityManagerFactory. With the container (Java EE compliant application server for example), you get the option of having the EntityManager injected in your code. The workings of the container managed EntityManager and persistence context is beyond the scope of this series of articles as the objective is to appreciate the JPA with as look support of tools as possible.

In order to get an EntityManagerFactory we need to consider what JPA calls Persistence Context. Though not directly used in JPA applications, the persistence context is closely linked with the EntityManager in a sense that it is the persistence context that defines the entities that are managed by the EntityManager. A persistence context is defined in an XML file which is generally named persistence.xml. In this XML file are persistence units which contains such information as connection parameters (server name, database name, database url, driver, username, password) and any additional properties that can be used by the particular JPA provider. Besides, the connection parameter the persistence unit also specifics the type of transaction that are to be used by EntityManagers so created from the persistence unit.

sample persistence.xml

<?xml version=”1.0″ encoding=”UTF-8″?>
<persistence version=”1.0″
xmlns=http://java.sun.com/xml/ns/persistence
xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance
xsi:schemaLocation=”http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd”>
  <persistence-unit name=”ContactsService” transaction-type=”RESOURCE_LOCAL”>

<provider>oracle.toplink.essentials.PersistenceProvider</provider>
<class>model.Client</class>
<class>model.Network</class>
<class>model.AirTimeCard</class>
<class>model.NetworkPrefix</class>
<class>model.Hotel</class>
<class>model.Room</class>
<class>model.Feature</class>
<class>model.FeatureGroup</class>
<properties>

  <property name=”toplink.jdbc.url” value=”jdbc:derby:atbankdb;create=true”/>
  <property name=”toplink.jdbc.driver” value=”org.apache.derby.jdbc.EmbeddedDriver”/>
</properties>

</persistence-unit>

The sample persistence.xml file above defines a persistence unit called “ContactsService” with a transaction type specified as “RESOURCE LOCAL”. This means that we are using entity level transactions which enables us to begin a transaction by calling methods of the EntityManager; specifically em.getTransaction(). We have the option of using JTA (Java Transaction API) which is application for container managed EntityManager. Additional in the persistence unit, we define the provider that we are using. We make use of the toplink Provider. Somewhere in its lifetime, it was owned by Oracle hence the reference to Oracle. TopLink is now an open source project. Other providers that you can use within a persistence unit include Hibernate, OpenJPA and others. The difference is in implementation; for example both Hibernate and OpenJPA are implemented to be as robust as possible with an aim to be relevant to high demand production environments.

As mentioned earlier, the persistence unit defines the entities that are managed within a persistence context which becomes accessible to your code through an EntityManager.

In the Hotel application, since it is a Java SE application, we use the Persistence bootstrap loader to create an EntityManagerFactory.

Code Sample

package controller;

import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityManager;
import javax.persistence.Persistence;

/**
* AbstractController class
*
* @author Imma
*/

public abstract class AbstractController
{
    protected EntityManagerFactory emf;

    protected EntityManager getEntityManager(){
        if(emf == null){
            emf = Persistence.createEntityManagerFactory(“ContactsService”);
        }

        return emf.createEntityManager();
    }
}

 

Instead of having to call the bootstrap load in all of our Data Access Layer classes, we can take advantage of inheritance by creating an abstract class with the appropriate method to create an EntityManager. Notice that an EntityManagerFactory is declared as protected, making it accessible to all sub-classes. In addition to that, we have a method that returns an EntityManager for the ContactsService persistence unit (defined in the preceding persistence.xml).

Sample Code

package controller;

import java.util.Collection;
import model.Network;
import javax.persistence.EntityManager;
import javax.persistence.Query;

import model.Hotel;

public class HotelController extends AbstractController
{
    public Collection<Hotel> getHotels(){
        EntityManager em = getEntityManager();

        try{
            Query q = em.createQuery(“SELECT h FROM Hotel AS h ORDER BY h.name”);
            return (Collection<Hotel>) q.getResultList();
        }finally{
            em.close();
        }
    }

    /**
     *
     */
    public Hotel addHotel(Hotel hotel){
        EntityManager em = getEntityManager();
        try{
            em.getTransaction().begin();
            em.persist(hotel);
            em.getTransaction().commit();
            return hotel;
        }finally{
            em.close();
        }
    }

   /**
     * Update Hotel. As you may have already inferred this method is used to update the
     * details of entity (Hotel entity to be exact) that is already stored in the
     * database. We have two options of going about the update.
     * 
     *
     * 1)    We can used the entity manager to locate the entity in the database.
     *       This act of locating the entity gives a managed hotel entity (assuming it
     *       has found in the first place). What this means is that the entity manager
     *       is keep track of any changes made on the attached (managed) entity.
     *

     *       If the retrieval of the entity occurred outside of a transaction, we can
     *       start a transaction; It is within transaction boundaries that the entity’s 
     *       properties are changed and upon committing the transaction, our changes are
     *       then sent to the database.
     *
     * 2)    The second option we have at our disposal is to used the entity manager’s 
     *       merge method. It is not as involving as the method described in one above
     *       which is a good thing if you want to keep your code simple and clean.
     *
     * @return void
     */
    public void update(Hotel hotel){
        EntityManager em = getEntityManager();
        try{
            em.getTransaction().begin();
            em.merge(hotel);
            em.getTransaction().commit();
        }finally{
            em.close();
        }
    }

    public Hotel getHotelById(int hotelId){
        EntityManager em = getEntityManager();
        Hotel hotel = em.find(Hotel.class, hotelId);

        return hotel;
    }

    public Collection<Hotel> getHotelByName(String hotelName){
        EntityManager em = getEntityManager();
        Query query = em.createQuery(“SELECT h FROM Hotel h WHERE h.name LIKE :name“);

  StringBuilder sb = new StringBuilder(“%”);
  sb.append(hotelName);
  sb.append(“%”);

  query.setParameter(“name”, sb.toString());

  return (Collection<Hotel>) query.getResultList();

    }
}

5 Comments