1
|
// $Id$
|
2
|
/**
|
3
|
* Copyright (C) 2015 EDIT
|
4
|
* European Distributed Institute of Taxonomy
|
5
|
* http://www.e-taxonomy.eu
|
6
|
*
|
7
|
* The contents of this file are subject to the Mozilla Public License Version 1.1
|
8
|
* See LICENSE.TXT at the top of this package for the full license terms.
|
9
|
*/
|
10
|
package eu.etaxonomy.cdm.persistence.hibernate;
|
11
|
|
12
|
import java.util.HashSet;
|
13
|
import java.util.Map;
|
14
|
import java.util.Set;
|
15
|
import java.util.concurrent.ConcurrentHashMap;
|
16
|
|
17
|
import org.hibernate.Hibernate;
|
18
|
import org.hibernate.HibernateException;
|
19
|
import org.hibernate.Session;
|
20
|
import org.hibernate.event.spi.MergeEvent;
|
21
|
import org.hibernate.event.spi.MergeEventListener;
|
22
|
|
23
|
import eu.etaxonomy.cdm.model.common.CdmBase;
|
24
|
|
25
|
/**
|
26
|
* @author cmathew
|
27
|
* @date 23 Sep 2015
|
28
|
*
|
29
|
*/
|
30
|
public class PostMergeEntityListener implements MergeEventListener {
|
31
|
private static final long serialVersionUID = 1565797119368313987L;
|
32
|
|
33
|
private static Map<Session, Set<CdmBase>> newEntitiesMap = new ConcurrentHashMap<Session, Set<CdmBase>>();
|
34
|
|
35
|
public static void addSession(Session session) {
|
36
|
newEntitiesMap.put(session, new HashSet<CdmBase>());
|
37
|
}
|
38
|
|
39
|
public static void removeSession(Session session) {
|
40
|
newEntitiesMap.remove(session);
|
41
|
}
|
42
|
|
43
|
public static Set<CdmBase> getNewEntities(Session session) {
|
44
|
return newEntitiesMap.get(session);
|
45
|
}
|
46
|
|
47
|
@Override
|
48
|
public void onMerge(MergeEvent event) throws HibernateException {
|
49
|
|
50
|
}
|
51
|
|
52
|
@Override
|
53
|
public void onMerge(MergeEvent event, Map copiedAlready) throws HibernateException {
|
54
|
// any new entities are added to a map which is retrieved at the end of the
|
55
|
// CdmEntityDaoBase.merge(T transientObject, boolean returnTransientEntity) call
|
56
|
if(event.getOriginal() != null && CdmBase.class.isAssignableFrom(event.getOriginal().getClass()) &&
|
57
|
event.getResult() != null && CdmBase.class.isAssignableFrom(event.getResult().getClass())) {
|
58
|
CdmBase original = (CdmBase) event.getOriginal();
|
59
|
CdmBase result = (CdmBase) event.getResult();
|
60
|
if(original != null && Hibernate.isInitialized(original) && original.getId() == 0 &&
|
61
|
result != null && Hibernate.isInitialized(result) && result.getId() > 0) {
|
62
|
original.setId(result.getId());
|
63
|
Set<CdmBase> newEntities = newEntitiesMap.get(event.getSession());
|
64
|
if(newEntities != null) {
|
65
|
newEntities.add(result);
|
66
|
}
|
67
|
}
|
68
|
}
|
69
|
|
70
|
|
71
|
}
|
72
|
|
73
|
}
|