Adding JPA to the address book demo

Petter Holmström

Introduction

The Vaading address book tutorial (the one hour version, that is) does a very good job introducing the different parts of Vaadin. However, it only uses an in-memory data source with randomly generated data. This may be sufficient for demonstration purposes, but not for any real world applications that manage data. Therefore, in this article, we are going to replace the tutorial’s in-memory data source with the Java Persistence API (JPA) and also utilize some of the new JEE 6 features of GlassFish 3.

Prerequisites

In order to fully understand this article, you should be familiar with JEE and JPA development and you should also have read through the Vaadin tutorial.

If you want to try out the code in this article you should get the latest version of GlassFish 3 (build 67 was used for this article) and Apache Ant 1.7. You also need to download the source code. Note, that you have to edit the build.xml file to point to the correct location of the GlassFish installation directory before you can use it!

The System Architecture

The architecture of the application is presented in the following diagram:

System architecture diagram

In addition to the Vaadin UI created in the tutorial, we will add a stateless Enterprise Java Bean (EJB) to act as a facade to the database. The EJB will in turn use JPA to communicate with a JDBC data source (in this example, the built-in jdbc/sample data source).

Refactoring the Domain Model

Before doing anything else, we have to modify the domain model of the Address Book example.

The Person class

In order to use JPA, we have to add JPA annotations to the Person class:

Java

  1. // Imports omitted
  2. @Entity
  3. public class Person implements Serializable {
  4. @Id
  5. @GeneratedValue(strategy = GenerationType.IDENTITY)
  6. private Long id;
  7. @Version
  8. @Column(name = "OPTLOCK")
  9. private Long version;
  10. private String firstName = "";
  11. private String lastName = "";
  12. private String email = "";
  13. private String phoneNumber = "";
  14. private String streetAddress = "";
  15. private Integer postalCode = null;
  16. private String city = "";
  17. public Long getId() {
  18. return id;
  19. }
  20. public Long getVersion() {
  21. return version;
  22. }
  23. // The rest of the methods omitted
  24. }

As we do not need to fit the domain model onto an existing database, the annotations become very simple. We have only marked the class as being an entity and added an ID and a version field.

The PersonReference class

There are many advantages with using JPA or any other Object Persistence Framework (OPF). The underlying database gets completely abstracted away and we can work with the domain objects themselves instead of query results and records. We can detach domain objects, send them to a client using a remote invocation protocol, then reattach them again.

However, there are a few use cases where using an OPF is not such a good idea: reporting and listing. When a report is generated or a list of entities is presented to the user, normally only a small part of the data is actually required. When the number of objects to fetch is large and the domain model is complex, constructing the object graphs from the database can be a very lengthy process that puts the users’ patience to the test – especially if they are only trying to select a person’s name from a list.

Many OPFs support lazy loading of some form, where references and collections are fetched on demand. However, this rarely works outside the container, e.g. on the other side of a remoting connection.

One way of working around this problem is to let reports and lists access the database directly using SQL. This is a fast approach, but it also couples the code to a particular SQL dialect and therefore to a particular database vendor.

In this article, we are going to select the road in the middle – we will only fetch the property values we need instead of the entire object, but we will use PQL and JPA to do so. In this example, this is a slight overkill as we have a very simple domain model. However, we do this for two reasons: Firstly, as Vaadin is used extensively in business applications where the domain models are complex, we want to introduce this pattern in an early stage. Secondly, it makes it easier to plug into Vaadin’s data model.

In order to implement this pattern, we need to introduce a new class, namely PersonReference:

Java

  1. import com.vaadin.data.Item;
  2. import com.vaadin.data.Property;
  3. import com.vaadin.data.util.ObjectProperty;
  4. // Some imports omitted
  5. public class PersonReference implements Serializable, Item {
  6. private Long personId;
  7. private Map<Object, Property> propertyMap;
  8. public PersonReference(Long personId, Map<String, Object> propertyMap) {
  9. this.personId = personId;
  10. this.propertyMap = new HashMap<Object, Property>();
  11. for (Map.Entry<Object, Property> entry : propertyMap.entrySet()) {
  12. this.propertyMap.put(entry.getKey(), new ObjectProperty(entry.getValue()));
  13. }
  14. }
  15. public Long getPersonId() {
  16. return personId;
  17. }
  18. public Property getItemProperty(Object id) {
  19. return propertyMap.get(id);
  20. }
  21. public Collection<?> getItemPropertyIds() {
  22. return Collections.unmodifiableSet(propertyMap.keySet());
  23. }
  24. public boolean addItemProperty(Object id, Property property) {
  25. throw new UnsupportedOperationException("Item is read-only.");
  26. }
  27. public boolean removeItemProperty(Object id) {
  28. throw new UnsupportedOperationException("Item is read-only.");
  29. }
  30. }

The class contains the ID of the actual Person object and a Map of property values. It also implements the com.vaadin.data.Item interface, which makes it directly usable in Vaadin’s data containers.

The QueryMetaData class

Before moving on to the EJB, we have to introduce yet another class, namely QueryMetaData:

Java

  1. // Imports omitted
  2. public class QueryMetaData implements Serializable {
  3. private boolean[] ascending;
  4. private String[] orderBy;
  5. private String searchTerm;
  6. private String propertyName;
  7. public QueryMetaData(String propertyName, String searchTerm, String[] orderBy, boolean[] ascending) {
  8. this.propertyName = propertyName;
  9. this.searchTerm = searchTerm;
  10. this.ascending = ascending;
  11. this.orderBy = orderBy;
  12. }
  13. public QueryMetaData(String[] orderBy, boolean[] ascending) {
  14. this(null, null, orderBy, ascending);
  15. }
  16. public boolean[] getAscending() {
  17. return ascending;
  18. }
  19. public String[] getOrderBy() {
  20. return orderBy;
  21. }
  22. public String getSearchTerm() {
  23. return searchTerm;
  24. }
  25. public String getPropertyName() {
  26. return propertyName;
  27. }
  28. }

As the class name suggests, this class contains query meta data such as ordering and filtering information. We are going to look at how it is used in the next section.

The Stateless EJB

We are now ready to begin designing the EJB. As of JEE 6, an EJB is no longer required to have an interface. However, as it is a good idea to use interfaces at the boundaries of system components, we will create one nonetheless:

Java

  1. // Imports omitted
  2. @TransactionAttribute
  3. @Local
  4. public interface PersonManager {
  5. public List<PersonReference> getPersonReferences(QueryMetaData queryMetaData, String... propertyNames);
  6. public Person getPerson(Long id);
  7. public Person savePerson(Person person);
  8. }

Please note the @TransactionAttribute and @Local annotations that instruct GlassFish to use container managed transaction handling, and to use local references, respectively. Next, we create the implementation:

Java

  1. // Imports omitted
  2. @Stateless
  3. public class PersonManagerBean implements PersonManager {
  4. @PersistenceContext
  5. protected EntityManager entityManager;
  6. public Person getPerson(Long id) {
  7. // Implementation omitted
  8. }
  9. public List<PersonReference> getPersonReferences(QueryMetaData queryMetaData, String... propertyNames) {
  10. // Implementation omitted
  11. }
  12. public Person savePerson(Person person) {
  13. // Implementation omitted
  14. }
  15. }

We use the @Stateless annotation to mark the implementation as a stateless session EJB. We also use the @PersistenceContext annotation to instruct the container to automatically inject the entity manager dependency. Thus, we do not have to do any lookups using e.g. JNDI.

Now we can move on to the method implementations.

Java

  1. public Person getPerson(Long id) {
  2. return entityManager.find(Person.class, id);
  3. }

This implementation is very straight-forward: given the unique ID, we ask the entity manager to look up the corresponding Person instance and return it. If no such instance is found, null is returned.

Java

  1. public List<PersonReference> getPersonReferences(QueryMetaData queryMetaData, String... propertyNames) {
  2. StringBuffer pqlBuf = new StringBuffer();
  3. pqlBuf.append("SELECT p.id");
  4. for (int i = 0; i < propertyNames.length; i++) {
  5. pqlBuf.append(",");
  6. pqlBuf.append("p.");
  7. pqlBuf.append(propertyNames[i]);
  8. }
  9. pqlBuf.append(" FROM Person p");
  10. if (queryMetaData.getPropertyName() != null) {
  11. pqlBuf.append(" WHERE p.");
  12. pqlBuf.append(queryMetaData.getPropertyName());
  13. if (queryMetaData.getSearchTerm() == null) {
  14. pqlBuf.append(" IS NULL");
  15. } else {
  16. pqlBuf.append(" = :searchTerm");
  17. }
  18. }
  19. if (queryMetaData != null && queryMetaData.getAscending().length > 0) {
  20. pqlBuf.append(" ORDER BY ");
  21. for (int i = 0; i < queryMetaData.getAscending().length; i++) {
  22. if (i > 0) {
  23. pqlBuf.append(",");
  24. }
  25. pqlBuf.append("p.");
  26. pqlBuf.append(queryMetaData.getOrderBy()[i]);
  27. if (!queryMetaData.getAscending()[i]) {
  28. pqlBuf.append(" DESC");
  29. }
  30. }
  31. }
  32. String pql = pqlBuf.toString();
  33. Query query = entityManager.createQuery(pql);
  34. if (queryMetaData.getPropertyName() != null && queryMetaData.getSearchTerm() != null) {
  35. query.setParameter("searchTerm", queryMetaData.getSearchTerm());
  36. }
  37. List<Object[]> result = query.getResultList();
  38. List<PersonReference> referenceList = new ArrayList<PersonReference>(result.size());
  39. HashMap<String, Object> valueMap;
  40. for (Object[] row : result) {
  41. valueMap = new HashMap<String, Object>();
  42. for (int i = 1; i < row.length; i++) {
  43. valueMap.put(propertyNames[i - 1], row[i]);
  44. }
  45. referenceList.add(new PersonReference((Long) row[0], valueMap));
  46. }
  47. return referenceList;
  48. }

This method is a little more complicated and also demonstrates the usage of the QueryMetaData class. What this method does is that it constructs a PQL query that fetches the values of the properties provided in the propertyNames array from the database. It then uses the QueryMetaData instance to add information about ordering and filtering. Finally, it executes the query and returns the result as a list of PersonReference instances.

The advantage with using QueryMetaData is that additional query options can be added without having to change the interface. We could e.g. create a subclass named AdvancedQueryMetaData with information about wildcards, result size limitations, etc.

Java

  1. public Person savePerson(Person person) {
  2. if (person.getId() == null)
  3. entityManager.persist(person);
  4. else
  5. entityManager.merge(person);
  6. return person;
  7. }

This method checks if person is persistent or transient, merges or persists it, respectively, and finally returns it. The reason why person is returned is that this makes the method usable for remote method calls. However, as this example does not need any remoting, we are not going to discuss this matter any further in this article.

Plugging Into the UI

The persistence component of our Address Book application is now completed. Now we just have to plug it into the existing user interface component. In this article, we are only going to look at some of the changes that have to be made to the code. That is, if you try to deploy the application with the changes presented in this article only, it will not work. For all the changes, please check the source code archive attached to this article.

Creating a New Container

First of all, we have to create a Vaadin container that knows how to read data from a PersonManager:

Java

  1. // Imports omitted
  2. public class PersonReferenceContainer implements Container, Container.ItemSetChangeNotifier {
  3. public static final Object[] NATURAL_COL_ORDER = new String[] {"firstName", "lastName", "email",
  4. "phoneNumber", "streetAddress", "postalCode", "city"};
  5. protected static final Collection<Object> NATURAL_COL_ORDER_COLL = Collections.unmodifiableList(
  6. Arrays.asList(NATURAL_COL_ORDER)
  7. );
  8. protected final PersonManager personManager;
  9. protected List<PersonReference> personReferences;
  10. protected Map<Object, PersonReference> idIndex;
  11. public static QueryMetaData defaultQueryMetaData = new QueryMetaData(
  12. new String[]{"firstName", "lastName"}, new boolean[]{true, true});
  13. protected QueryMetaData queryMetaData = defaultQueryMetaData;
  14. // Some fields omitted
  15. public PersonReferenceContainer(PersonManager personManager) {
  16. this.personManager = personManager;
  17. }
  18. public void refresh() {
  19. refresh(queryMetaData);
  20. }
  21. public void refresh(QueryMetaData queryMetaData) {
  22. this.queryMetaData = queryMetaData;
  23. personReferences = personManager.getPersonReferences(queryMetaData, (String[]) NATURAL_COL_ORDER);
  24. idIndex = new HashMap<Object, PersonReference>(personReferences.size());
  25. for (PersonReference pf : personReferences) {
  26. idIndex.put(pf.getPersonId(), pf);
  27. }
  28. notifyListeners();
  29. }
  30. public QueryMetaData getQueryMetaData() {
  31. return queryMetaData;
  32. }
  33. public void close() {
  34. if (personReferences != null) {
  35. personReferences.clear();
  36. personReferences = null;
  37. }
  38. }
  39. public boolean isOpen() {
  40. return personReferences != null;
  41. }
  42. public int size() {
  43. return personReferences == null ? 0 : personReferences.size();
  44. }
  45. public Item getItem(Object itemId) {
  46. return idIndex.get(itemId);
  47. }
  48. public Collection<?> getContainerPropertyIds() {
  49. return NATURAL_COL_ORDER_COLL;
  50. }
  51. public Collection<?> getItemIds() {
  52. return Collections.unmodifiableSet(idIndex.keySet());
  53. }
  54. public List<PersonReference> getItems() {
  55. return Collections.unmodifiableList(personReferences);
  56. }
  57. public Property getContainerProperty(Object itemId, Object propertyId) {
  58. Item item = idIndex.get(itemId);
  59. if (item != null) {
  60. return item.getItemProperty(propertyId);
  61. }
  62. return null;
  63. }
  64. public Class<?> getType(Object propertyId) {
  65. try {
  66. PropertyDescriptor pd = new PropertyDescriptor((String) propertyId, Person.class);
  67. return pd.getPropertyType();
  68. } catch (Exception e) {
  69. return null;
  70. }
  71. }
  72. public boolean containsId(Object itemId) {
  73. return idIndex.containsKey(itemId);
  74. }
  75. // Unsupported methods omitted
  76. // addListener(..) and removeListener(..) omitted
  77. protected void notifyListeners() {
  78. ArrayList<ItemSetChangeListener> cl = (ArrayList<ItemSetChangeListener>) listeners.clone();
  79. ItemSetChangeEvent event = new ItemSetChangeEvent() {
  80. public Container getContainer() {
  81. return PersonReferenceContainer.this;
  82. }
  83. };
  84. for (ItemSetChangeListener listener : cl) {
  85. listener.containerItemSetChange(event);
  86. }
  87. }
  88. }

Upon creation, this container is empty. When one of the refresh(..) methods is called, a list of PersonReference`s are fetched from the `PersonManager and cached locally. Even though the database is updated, e.g. by another user, the container contents will not change before the next call to refresh(..).

To keep things simple, the container is read only, meaning that all methods that are designed to alter the contents of the container throw an exception. Sorting, optimization and lazy loading has also been left out (if you like, you can try to implement these yourself).

Modifying the PersonForm class

We now have to refactor the code to use our new container, starting with the PersonForm class. We begin with the part of the constructor that creates a list of all the cities currently in the container:

Java

  1. PersonReferenceContainer ds = app.getDataSource();
  2. for (PersonReference pf : ds.getItems()) {
  3. String city = (String) pf.getItemProperty("city").getValue();
  4. cities.addItem(city);
  5. }

We have changed the code to iterate a collection of PersonReference instances instead of Person instances.

Then, we will continue with the part of the buttonClick(..) method that saves the contact:

Java

  1. if (source == save) {
  2. if (!isValid()) {
  3. return;
  4. }
  5. commit();
  6. person = app.getPersonManager().savePerson(person);
  7. setItemDataSource(new BeanItem(person));
  8. newContactMode = false;
  9. app.getDataSource().refresh();
  10. setReadOnly(true);
  11. }

The code has actually become simpler, as the same method is used to save both new and existing contacts. When the contact is saved, the container is refreshed so that the new information is displayed in the table.

Finally, we will add a new method, editContact(..) for displaying and editing existing contacts:

Java

  1. public void editContact(Person person) {
  2. this.person = person;
  3. setItemDataSource(new BeanItem(person))
  4. newContactMode = false;
  5. setReadOnly(true);
  6. }

This method is almost equal to addContact() but uses an existing Person instance instead of a newly created one. It also makes the form read only, as the user is expected to click an Edit button to make the form editable.

Modifying the AddressBookApplication class

Finally, we are going to replace the old container with the new one in the main application class. We will start by adding a constructor:

Java

  1. public AddressBookApplication(PersonManager personManager) {
  2. this.personManager = personManager;
  3. }

This constructor will be used by a custom application servlet to inject a reference to the PersonManager EJB. When this is done, we move on to the init() method:

Java

  1. public void init() {
  2. dataSource = new PersonReferenceContainer(personManager);
  3. dataSource.refresh(); // Load initial data
  4. buildMainLayout();
  5. setMainComponent(getListView());
  6. }

The method creates a container and refreshes it in order to load the existing data from the database – otherwise, the user would be presented with an empty table upon application startup.

Next, we modify the code that is used to select contacts:

Java

  1. public void valueChange(ValueChangeEvent event) {
  2. Property property = event.getProperty();
  3. if (property == personList) {
  4. Person person = personManager.getPerson((Long) personList.getValue());
  5. personForm.editContact(person);
  6. }
  7. }

The method gets the ID of the currently selected person and uses it to lookup the Person instance from the database, which is then passed to the person form using the newly created editContact(..) method.

Next, we modify the code that handles searches:

Java

  1. public void search(SearchFilter searchFilter) {
  2. QueryMetaData qmd = new QueryMetaData((String) searchFilter.getPropertyId(), searchFilter.getTerm(),
  3. getDataSource().getQueryMetaData().getOrderBy(),
  4. getDataSource().getQueryMetaData().getAscending());
  5. getDataSource().refresh(qmd);
  6. showListView();
  7. // Visual notification omitted
  8. }

Instead of filtering the container, this method constructs a new QueryMetaData instance and refreshes the data source. Thus, the search operation is performed in the database and not in the container itself.

As we have removed container filtering, we also have to change the code that is used to show all contacts:

Java

  1. public void itemClick(ItemClickEvent event) {
  2. if (event.getSource() == tree) {
  3. Object itemId = event.getItemId();
  4. if (itemId != null) {
  5. if (itemId == NavigationTree.SHOW_ALL) {
  6. getDataSource().refresh(PersonReferenceContainer.defaultQueryMetaData);
  7. showListView();
  8. } else if (itemId == NavigationTree.SEARCH) {
  9. showSearchView();
  10. } else if (itemId instanceof SearchFilter) {
  11. search((SearchFilter) itemId);
  12. }
  13. }
  14. }
  15. }

Instead of removing the filters, this method refreshes the data source using the default query meta data.

Creating a Custom Servlet

The original tutorial used an ApplicationServlet configured in web.xml to start the application. In this version, however, we are going to create our own custom servlet. By doing this, we can let GlassFish inject the reference to the PersonManager EJB using annotations, which means that we do not need any JDNI look ups at all. As a bonus, we get rid of the web.xml file as well thanks to the new JEE 6 @WebServlet annotation. The servlet class can be added as an inner class to the main application class:

Java

  1. @WebServlet(urlPatterns = "/*")
  2. public static class Servlet extends AbstractApplicationServlet {
  3. @EJB
  4. PersonManager personManager;
  5. @Override
  6. protected Application getNewApplication(HttpServletRequest request) throws ServletException {
  7. return new AddressBookApplication(personManager);
  8. }
  9. @Override
  10. protected Class<? extends Application> getApplicationClass() throws ClassNotFoundException {
  11. return AddressBookApplication.class;
  12. }
  13. }

When the servlet is initialized by the web container, the PersonManager EJB will be automatically injected into the personManager field thanks to the @EJB annotation. This reference can then be passed to the main application class in the getNewApplication(..) method.

Classical Deployment

Packaging this application into a WAR is no different from the Hello World example. We just have to remember to include the persistence.xml file (we are not going to cover the contents of this file in this article), otherwise JPA will not work. Note, that as of JEE 6, we do not need to split up the application into a different bundle for the EJB and another for the UI. We also do not need any other configuration files than the persistence unit configuration file.

The actual packaging can be done using the following Ant target:

XML

  1. <target name="package-with-vaadin" depends="compile">
  2. <mkdir dir="${dist.dir}"/>
  3. <war destfile="${dist.dir}/${ant.project.name}-with-vaadin.war" needxmlfile="false">
  4. <lib file="${vaadin.jar}"/>
  5. <classes dir="${build.dir}"/>
  6. <fileset dir="${web.dir}" includes="**"/>
  7. </war>
  8. </target>

Once the application has been packaged, it can be deployed like so, using the asadmin tool that comes with GlassFish:

bash

  1. $ asadmin deploy /path/to/addressbook-with-vaadin.war

Note, that the Java DB database bundled with GlassFish must be started prior to deploying the application. Now we can test the application by opening a web browser and navigating to http://localhost:8080/addressbook-with-vaadin. The running application should look something like this:

Running application screenshot

OSGi Deployment Options

The OSGi support of GlassFish 3 introduces some new possibilities for Vaadin development. If the Vaadin library is deployed as an OSGi bundle, we can package and deploy the address book application without the Vaadin library. The following Ant target can be used to create the WAR:

XML

  1. <target name="package-without-vaadin" depends="compile">
  2. <mkdir dir="${dist.dir}"/>
  3. <war destfile="${dist.dir}/${ant.project.name}-without-vaadin.war" needxmlfile="false">
  4. <classes dir="${build.dir}"/>
  5. <fileset dir="${web.dir}" includes="**"/>
  6. </war>
  7. </target>

Summary

In this article, we have extended the Address Book demo to use JPA instead of the in-memory container, with an EJB acting as the facade to the database. Thanks to annotations, the application does not contain a single JNDI lookup, and thanks to JEE 6, the application can be deployed as a single WAR.