Purpose

The purpose of the model repository is to save off the model between an edit and save action. Often times this is need when using detached objects with JPA or Hibernate. This is also needed in instances where optimistic locking is used.

Use Case

The model repository is designed to be used for the typical edit/save use case that many web applications must handle. The use case begins with the user choosing to edit an object in the system. The system loads the given object from the database and displays the object for the user to edit. At the same time, the object should be stored in the session so it can be retrieved later. Once the user is finished editing the object, the user clicks the save button and the page is submited back to the application. At this point, the object is restored from the session and the new values are applied to the newly restored object. Then the object is persisted to the database, so the new values are not lost.

Implementation

This functionality can be implemented very easily with the scope plugin. The first step is to define a place to store the model in the session. This key is used for all actions. Any previous value is overwritten with the new value for the current action. This ensures that the session is not filled of with random values from each action.

Here is the interface that hold our global session key for all action models:

/**
 * The location in the session where the domain model is stored between an edit
 * and a save.
 */
public interface ModelRepo {
	/**
	 * The session key where domain model is stored.
	 */
	public static String DOMAIN_MODEL = "DOMAIN_MODEL";
}

Now simply annotate your domain model with an @In and @Out session annotation using the string constant from above as the session key:

public class ExampleAction extends ActionSupport {

	@In(scope = ScopeType.SESSION, value = ModelRepo.DOMAIN_MODEL)
	@Out(scope = ScopeType.SESSION, value = ModelRepo.DOMAIN_MODEL)
	private ExampleBean exampleBean;

	...

	public String edit() {
		...
		return SUCCESS;
	}

	public String save() {
		...
		return SUCCESS;
	}
}

That's all. After the edit, the domain model will be stored in the session. On the save, the model will be restored before the new values are applied.

Model Repository vs. params-prepare-params

An alternative to the model repository is to use the params-prepare-params interceptor stack. The params-prepare-params interceptor stack requires the object you are editing to be re-read from the database. In cases where optimistic locking is used, this completely circumvents the version field. In these cases, the originally read object should be used when saving the object.

  • No labels