source: VirtualCollectionRegistry/trunk/VirtualCollectionRegistry/src/main/java/eu/clarin/cmdi/virtualcollectionregistry/gui/VolatileEntityModel.java @ 5446

Last change on this file since 5446 was 5446, checked in by Twan Goosen, 10 years ago

Volatile entity model: only detach if object not null and already managed by persistence context

File size: 1.9 KB
Line 
1package eu.clarin.cmdi.virtualcollectionregistry.gui;
2
3import eu.clarin.cmdi.virtualcollectionregistry.model.IdentifiedEntity;
4import javax.persistence.EntityManager;
5import org.apache.wicket.model.IModel;
6import org.slf4j.Logger;
7import org.slf4j.LoggerFactory;
8
9/**
10 * Model for volatile entity objects: objects that are managed by a persistence
11 * context but do not get persisted before the end of the request cycle and
12 * therefore lose their connection to the context. This model merges the model
13 * object with the persistence context on the first call of {@link #getObject()
14 * } after {@link #detach() }.
15 *
16 * @author twagoo
17 * @see EntityManager#merge(java.lang.Object)
18 */
19public class VolatileEntityModel<T extends IdentifiedEntity> implements IModel<T> {
20
21    private final static Logger logger = LoggerFactory.getLogger(VolatileEntityModel.class);
22    private T object;
23    private boolean attached;
24
25    public VolatileEntityModel(T object) {
26        this.object = object;
27        attached = true;
28    }
29
30    /**
31     *
32     * @return the previously stored object or a merged copy of it if the model
33     * was detached
34     */
35    @Override
36    public T getObject() {
37        if (!attached) {
38            attach();
39        }
40        return object;
41    }
42
43    private void attach() {
44        logger.trace("Merging volatile object ({}) into persistence context", object);
45        if (object != null && object.getId() != null) {
46            final EntityManager em = Application.get().getDataStore().getEntityManager();
47            object = em.merge(object);
48        }
49        attached = true;
50    }
51
52    @Override
53    public void setObject(T object) {
54        this.object = object;
55    }
56
57    @Override
58    public void detach() {
59        logger.trace("Detaching volatile object ({})", object);
60        // set flag so that on next call to getObject() object will be merged
61        attached = false;
62    }
63
64}
Note: See TracBrowser for help on using the repository browser.