Now as example of a possible use of LoadableDetachableModel
, we will
build a model designed to work with entities managed via JPA. To
understand the following code a basic knowledge of JPA is required
even if we won't go into the detail of this standard.
The following model is provided for example purposes only and is not
intended to be used in production environment. Important aspects such
as transaction management are not taken into account and you should
rework the code before considering to use it.
public class JpaLoadableModel<T> extends LoadableDetachableModel<T> {
private EntityManagerFactory entityManagerFactory;
private Class<T> entityClass;
private Serializable identifier;
private List<Object> constructorParams;
public JpaLoadableModel(EntityManagerFactory entityManagerFactory, T entity) {
super();
PersistenceUnitUtil util = entityManagerFactory.getPersistenceUnitUtil();
this.entityManagerFactory = entityManagerFactory;
this.entityClass = (Class<T>) entity.getClass();
this.identifier = (Serializable) util.getIdentifier(entity);
setObject(entity);
}
@Override protected T load() {
T entity = null;
if(identifier != null) {
EntityManager entityManager = entityManagerFactory.createEntityManager();
entity = entityManager.find(entityClass, identifier);
}
return entity;
}
@Override protected void onDetach() {
super.onDetach();
T entity = getObject();
PersistenceUnitUtil persistenceUtil = entityManagerFactory.getPersistenceUnitUtil();
if(entity == null) return;
identifier = (Serializable) persistenceUtil.getIdentifier(entity);
}
}
The constructor of the model takes as input two parameters: an
implementation of the JPA interface
javax.persistence.EntityManagerFactory
to manage JPA entities and the
entity that must be handled by this model. Inside its constructor the
model saves the class of the entity and its id (which could be null if
the entity has not been persisted yet). These two informations are
required to retrieve the entity at a later time and are used by the
load method.
onDetach
is responsible for updating the entity id before detachment
occurs. The id can change the first time an entity is persisted (JPA
generates a new id and assigns it to the entity). Please note that
this model is not responsible for saving any changes occurred to the
entity object before it is detached. If we don't want to loose these
changes we must explicitly persist the entity before the detaching
phase occurs.
Since the model of this example holds a reference to the EntityManagerFactory
, the implementation in use must be Serializable
.
LoadableDetachableModel
的 Wicket 6.x 版本。 - Hendy Irawan