Wicket in Action

Building a smart EntityModel

30 September 2008, by ivaynberg

A lot of Wicket applications use an ORM framework to work with the database. Because ORMs provide a generic mechanism for loading entities we can create a generic Wicket model that can simplify binding between ORM and Wicket. In this article I will walk you through creating an EntityModel that will make using Wicket and ORM fun, read inside...


In order to load an entity from the database we need two pieces of information: entity’s class and id. Since there is no standard way to get an id from an object we will create an interface that will standardize the process:

1 public interface Identifiable<T extends Serializable>
2 {
3  T getId();
4 }

The simplest entity model can then look like this:

 1 public abstract class AbstractEntityModel<T extends Identifiable< ? >>
 2  extends
 3  LoadableDetachableModel<T>
 4 {
 5  private Class clazz;
 6  private Serializable id;
 7 
 8  public AbstractEntityModel(T entity)
 9  {
10  clazz = entity.getClass();
11  id = entity.getId();
12  }
13 
14  public AbstractEntityModel(Class< ? extends T> clazz, Serializable id)
15  {
16  this.clazz = clazz;
17  this.id = id;
18  }
19 
20  @Override
21  protected T load()
22  {
23  return load(clazz, id);
24  }
25 
26  protected abstract T load(Class clazz, Serializable id);
27 }
  • 26: the method used to perform the actual loading of entity from the ORM

This model can load any entity given an instance or a class and id, and will detach itself at the end of request. The model is abstract because the way to retrieve a handle to the ORM session varies from application to application. For example, in my project that uses Salve's dependency injection and Hibernate a concrete implementation will look like this:

 1 public class EntityModel<T> extends AbstractEntityModel<T>
 2 {
 3  @Dependency
 4  private Session session;
 5 
 6  @Override
 7  protected Identifiable load(Class clazz, Serializable id)
 8  {
 9  return session.get(clazz, id);
10  }
11 }
  • 3: Salve annotation that will make sure field session is injected with the current hibernate session
  • 7-10: concrete implementation of the #load() method using hibernate Session

Handling Errors

There are cases when a user deletes an object from the database that another user is currently viewing in the UI. In this case when the UI tries to render and calls getObject() on our EntityModel it will return null. There is nothing worse in the log then a cryptic NullPointerExcepton. A much better approach is to check for this condition and throw a type of exception that can be intercepted and processed appropriately by the UI.

 1 public abstract class AbstractEntityModel<T extends Identifiable< ? >>
 2  extends
 3  LoadableDetachableModel<T>
 4 {
 5  
 6  @Override
 7  protected T load()
 8  {
 9  T entity = load(clazz, id);
10  if (entity == null)
11  {
12  throw new EntityNotFoundException(clazz, id);
13  }
14  return entity;
15  }
16 
17  }
  • 10-13: built-in null check for better error reporting

Then in our RequestCycle subclass:

 1 public class MyRequestCycle extends WebRequestCycle
 2 {
 3  @Override
 4  public Page onRuntimeException(Page page, RuntimeException e)
 5  {
 6  if (e instanceof EntityNotFoundException)
 7  {
 8  return new EntityNotFoundErrorPage((EntityNotFoundException)e);
 9  }
10  else
11  {
12  return super.onRuntimeException(page, e);
13  }
14  }
15 
16 }

EntityNotFoundErrorPage can present a user-friendly message explaining why the error happened.

Using EntityModel to bind to Forms

Suppose the following code:

 1 public class EditPersonPage extends WebPage
 2 {
 3  public EditPersonPage(Long personId)
 4  {
 5  this(new EntityModel<Person>(Person.class, personId));
 6  }
 7 
 8  private EditPersonPage(IModel<Person> model)
 9  {
10 
11  Form<Person> form = new Form<Person>("form", new CompoundPropertyModel<Person>(model))
12  {
13  @Override
14  public boolean process()
15  {
16  beginTransaction();
17  if (super.process())
18  {
19  commitTransaction();
20  return true;
21  }
22  else
23  {
24  rollbackTransaction();
25  return false;
26  }
27 
28  }
29  };
30 
31  add(form);
32 
33  form.add(new TextField<String>("name"));
34  }
35 }

When the form is submitted the following series of calls will be made:

  • Form#process()
    • beginTransaction()
    • super.proces()
      • Person p=EntityModel.getObject()
      • p.setName(name);
      • Form#onSubmit()

    • commitTransaction();
  • EntityModel#detach();

This is interesting because the Person entity is loaded and the TextField sets the value on the loaded Person inside the same transaction, which means this value will be persisted automatically by the ORM when the transaction ends. Any changes done to this form"s data are automatically reflected in the database without any extra code.

Our AbstractEntityModel is already good enough to handle this scenario, but what if we wanted to reuse our form to create a new entity instance instead of just editing one? If we had a way to do this we can then reuse any Form to create or edit an entity. To achieve this we need to add two things to our model:

  1. Ability to hold on to a transient entity instance (disable detaching while the entity is transient)
  2. Allow the model to intelligently begin detaching if a transient entity instance has become persistent between getObject() and detach()

Since it is not possible to override LoadableDetachableModel’s detach() we will have to convert our model to implement IModel directly – giving us full control:

 1 public abstract class AbstractEntityModel<T extends Identifiable< ? >> implements IModel<T>
 2 {
 3  private final Class clazz;
 4  private Serializable id;
 5 
 6  private T entity;
 7 
 8  public AbstractEntityModel(T entity)
 9  {
10  clazz = entity.getClass();
11  id = entity.getId();
12  this.entity = entity;
13  }
14 
15  public AbstractEntityModel(Class< ? extends T> clazz, Serializable id)
16  {
17  this.clazz = clazz;
18  this.id = id;
19  }
20 
21  public T getObject()
22  {
23  if (entity == null)
24  {
25  if (id != null)
26  {
27  entity = load(clazz, id);
28  if (entity == null)
29  {
30  throw new EntityNotFoundException(clazz, id);
31  }
32  }
33  }
34  return entity;
35  }
36 
37  public void detach()
38  {
39  if (entity != null)
40  {
41  if (entity.getId() != null)
42  {
43  id = entity.getId();
44  entity = null;
45  }
46  }
47  }
48 
49  protected abstract T load(Class clazz, Serializable id);
50 
51  public void setObject(T object)
52  {
53  throw new UnsupportedOperationException(getClass() 
54  " does not support #setObject(T entity)");
55  }
56 }
  • 6: cache for the entity instance that we keep for the request, only the first #getObject() call will populate it
  • 12: notice we initialize the cache if we have the instance
  • 25: guard so we only call #load() if we have a valid id
  • 39: guard from preventing detaching a detached model
  • 41: guard to make sure we do not null out a transient entity instance, we want to keep it until it is persisted
  • 43: if a transient instance was persisted keep its id so it can be reloaded
  • 44: now that we have a valid id we no longer need to keep the cache

From now on our EntityModel will hold on to the transient entity until it is persisted. If we subclass the Form in the previous example and override its onSubmit() to persist the entity the model will switch into persistent mode after the form is submitted. So, it doesn"t matter if the EntityModel given to that form contains a transient or a persistent instance of the entity, the model and therefore also the form will simply do the right thing.

That’s it for now. Perhaps if there is more interest in such models I will revisit this and add a couple of other useful features.

-->