1 | package eu.clarin.cmdi.virtualcollectionregistry.gui; |
---|
2 | |
---|
3 | import eu.clarin.cmdi.virtualcollectionregistry.model.IdentifiedEntity; |
---|
4 | import javax.persistence.EntityManager; |
---|
5 | import org.apache.wicket.model.IModel; |
---|
6 | import org.slf4j.Logger; |
---|
7 | import 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 | */ |
---|
19 | public 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 | } |
---|