/
DbSqlSession.java
executable file
·1585 lines (1365 loc) · 64.8 KB
/
DbSqlSession.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.activiti.engine.impl.db;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.activiti.engine.ActivitiException;
import org.activiti.engine.ActivitiOptimisticLockingException;
import org.activiti.engine.ActivitiWrongDbException;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.ProcessEngineConfiguration;
import org.activiti.engine.impl.DeploymentQueryImpl;
import org.activiti.engine.impl.ExecutionQueryImpl;
import org.activiti.engine.impl.HistoricActivityInstanceQueryImpl;
import org.activiti.engine.impl.HistoricDetailQueryImpl;
import org.activiti.engine.impl.HistoricProcessInstanceQueryImpl;
import org.activiti.engine.impl.HistoricTaskInstanceQueryImpl;
import org.activiti.engine.impl.HistoricVariableInstanceQueryImpl;
import org.activiti.engine.impl.JobQueryImpl;
import org.activiti.engine.impl.ModelQueryImpl;
import org.activiti.engine.impl.Page;
import org.activiti.engine.impl.ProcessDefinitionQueryImpl;
import org.activiti.engine.impl.ProcessInstanceQueryImpl;
import org.activiti.engine.impl.TaskQueryImpl;
import org.activiti.engine.impl.cfg.ProcessEngineConfigurationImpl;
import org.activiti.engine.impl.context.Context;
import org.activiti.engine.impl.db.upgrade.DbUpgradeStep;
import org.activiti.engine.impl.interceptor.Session;
import org.activiti.engine.impl.persistence.cache.CachedEntity;
import org.activiti.engine.impl.persistence.cache.EntityCache;
import org.activiti.engine.impl.persistence.entity.Entity;
import org.activiti.engine.impl.persistence.entity.ExecutionEntity;
import org.activiti.engine.impl.persistence.entity.PropertyEntity;
import org.activiti.engine.impl.util.IoUtil;
import org.activiti.engine.impl.util.ReflectUtil;
import org.apache.ibatis.session.SqlSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*/
public class DbSqlSession implements Session {
private static final Logger log = LoggerFactory.getLogger(DbSqlSession.class);
protected static final Pattern CLEAN_VERSION_REGEX = Pattern.compile("\\d\\.\\d*");
protected static final String LAST_V5_VERSION = "5.99.0.0";
protected static final List<ActivitiVersion> ACTIVITI_VERSIONS = new ArrayList<ActivitiVersion>();
static {
/* Previous */
ACTIVITI_VERSIONS.add(new ActivitiVersion("5.7"));
ACTIVITI_VERSIONS.add(new ActivitiVersion("5.8"));
ACTIVITI_VERSIONS.add(new ActivitiVersion("5.9"));
ACTIVITI_VERSIONS.add(new ActivitiVersion("5.10"));
ACTIVITI_VERSIONS.add(new ActivitiVersion("5.11"));
// 5.12.1 was a bugfix release on 5.12 and did NOT change the version in ACT_GE_PROPERTY
// On top of that, DB2 create script for 5.12.1 was shipped with a 'T' suffix ...
ACTIVITI_VERSIONS.add(new ActivitiVersion("5.12",
Arrays.asList("5.12.1",
"5.12T")));
ACTIVITI_VERSIONS.add(new ActivitiVersion("5.13"));
ACTIVITI_VERSIONS.add(new ActivitiVersion("5.14"));
ACTIVITI_VERSIONS.add(new ActivitiVersion("5.15"));
ACTIVITI_VERSIONS.add(new ActivitiVersion("5.15.1"));
ACTIVITI_VERSIONS.add(new ActivitiVersion("5.16"));
ACTIVITI_VERSIONS.add(new ActivitiVersion("5.16.1"));
ACTIVITI_VERSIONS.add(new ActivitiVersion("5.16.2-SNAPSHOT"));
ACTIVITI_VERSIONS.add(new ActivitiVersion("5.16.2"));
ACTIVITI_VERSIONS.add(new ActivitiVersion("5.16.3.0"));
ACTIVITI_VERSIONS.add(new ActivitiVersion("5.16.4.0"));
ACTIVITI_VERSIONS.add(new ActivitiVersion("5.17.0.0"));
ACTIVITI_VERSIONS.add(new ActivitiVersion("5.17.0.1"));
ACTIVITI_VERSIONS.add(new ActivitiVersion("5.17.0.2"));
ACTIVITI_VERSIONS.add(new ActivitiVersion("5.18.0.0"));
ACTIVITI_VERSIONS.add(new ActivitiVersion("5.18.0.1"));
ACTIVITI_VERSIONS.add(new ActivitiVersion("5.20.0.0"));
ACTIVITI_VERSIONS.add(new ActivitiVersion("5.20.0.1"));
ACTIVITI_VERSIONS.add(new ActivitiVersion("5.20.0.2"));
ACTIVITI_VERSIONS.add(new ActivitiVersion("5.21.0.0"));
/*
* Version 5.18.0.1 is the latest v5 version in the list here, although if you would look at the v5 code,
* you'll see there are a few other releases afterwards.
*
* The reasoning is as follows: after 5.18.0.1, no database changes were done anymore.
* And if there would be database changes, they would have been part of both 5.x _and_ 6.x upgrade scripts.
* The logic below will assume it's one of these releases in case it isn't found in the list here
* and do the upgrade from the 'virtual' release 5.99.0.0 to make sure th v6 changes are applied.
*/
// This is the latest version of the 5 branch. It's a 'virtual' version cause it doesn't exist, but it is
// there to make sure all previous version can upgrade to the 6 version correctly.
ACTIVITI_VERSIONS.add(new ActivitiVersion(LAST_V5_VERSION));
// Version 6
ACTIVITI_VERSIONS.add(new ActivitiVersion("6.0.0.0"));
ACTIVITI_VERSIONS.add(new ActivitiVersion("6.0.0.1"));
ACTIVITI_VERSIONS.add(new ActivitiVersion("6.0.0.2"));
ACTIVITI_VERSIONS.add(new ActivitiVersion("6.0.0.3"));
/* Current */
ACTIVITI_VERSIONS.add(new ActivitiVersion(ProcessEngine.VERSION));
}
protected SqlSession sqlSession;
protected DbSqlSessionFactory dbSqlSessionFactory;
protected EntityCache entityCache;
protected Map<Class<? extends Entity>, Map<String, Entity>> insertedObjects
= new HashMap<Class<? extends Entity>, Map<String, Entity>>();
protected Map<Class<? extends Entity>, Map<String, Entity>> deletedObjects
= new HashMap<Class<? extends Entity>, Map<String, Entity>>();
protected Map<Class<? extends Entity>, List<BulkDeleteOperation>> bulkDeleteOperations
= new HashMap<Class<? extends Entity>, List<BulkDeleteOperation>>();
protected List<Entity> updatedObjects = new ArrayList<Entity>();
protected String connectionMetadataDefaultCatalog;
protected String connectionMetadataDefaultSchema;
public DbSqlSession(DbSqlSessionFactory dbSqlSessionFactory,
EntityCache entityCache) {
this.dbSqlSessionFactory = dbSqlSessionFactory;
this.sqlSession = dbSqlSessionFactory.getSqlSessionFactory().openSession();
this.entityCache = entityCache;
this.connectionMetadataDefaultCatalog = dbSqlSessionFactory.getDatabaseCatalog();
this.connectionMetadataDefaultSchema = dbSqlSessionFactory.getDatabaseSchema();
}
public DbSqlSession(DbSqlSessionFactory dbSqlSessionFactory,
EntityCache entityCache,
Connection connection,
String catalog,
String schema) {
this.dbSqlSessionFactory = dbSqlSessionFactory;
this.sqlSession = dbSqlSessionFactory.getSqlSessionFactory().openSession(connection); // Note the use of connection param here, different from other constructor
this.entityCache = entityCache;
this.connectionMetadataDefaultCatalog = catalog;
this.connectionMetadataDefaultSchema = schema;
}
// insert ///////////////////////////////////////////////////////////////////
public void insert(Entity entity) {
if (entity.getId() == null) {
String id = dbSqlSessionFactory.getIdGenerator().getNextId();
entity.setId(id);
}
Class<? extends Entity> clazz = entity.getClass();
if (!insertedObjects.containsKey(clazz)) {
insertedObjects.put(clazz,
new LinkedHashMap<String, Entity>()); // order of insert is important, hence LinkedHashMap
}
insertedObjects.get(clazz).put(entity.getId(),
entity);
entityCache.put(entity,
false); // False -> entity is inserted, so always changed
entity.setInserted(true);
}
// update
// ///////////////////////////////////////////////////////////////////
public void update(Entity entity) {
entityCache.put(entity,
false); // false -> we don't store state, meaning it will always be seen as changed
entity.setUpdated(true);
}
public int update(String statement,
Object parameters) {
String updateStatement = dbSqlSessionFactory.mapStatement(statement);
return getSqlSession().update(updateStatement,
parameters);
}
// delete
// ///////////////////////////////////////////////////////////////////
/**
* Executes a {@link BulkDeleteOperation}, with the sql in the statement parameter.
* The passed class determines when this operation will be executed: it will be executed
* when the particular class has passed in the {@link EntityDependencyOrder}.
*/
public void delete(String statement,
Object parameter,
Class<? extends Entity> entityClass) {
if (!bulkDeleteOperations.containsKey(entityClass)) {
bulkDeleteOperations.put(entityClass,
new ArrayList<BulkDeleteOperation>(1));
}
bulkDeleteOperations.get(entityClass).add(new BulkDeleteOperation(dbSqlSessionFactory.mapStatement(statement),
parameter));
}
public void delete(Entity entity) {
Class<? extends Entity> clazz = entity.getClass();
if (!deletedObjects.containsKey(clazz)) {
deletedObjects.put(clazz,
new LinkedHashMap<String, Entity>()); // order of insert is important, hence LinkedHashMap
}
deletedObjects.get(clazz).put(entity.getId(),
entity);
entity.setDeleted(true);
}
// select
// ///////////////////////////////////////////////////////////////////
@SuppressWarnings({"rawtypes"})
public List selectList(String statement) {
return selectList(statement,
null,
0,
Integer.MAX_VALUE);
}
@SuppressWarnings("rawtypes")
public List selectList(String statement,
Object parameter) {
return selectList(statement,
parameter,
0,
Integer.MAX_VALUE);
}
@SuppressWarnings("rawtypes")
public List selectList(String statement,
Object parameter,
boolean useCache) {
return selectList(statement,
parameter,
0,
Integer.MAX_VALUE,
useCache);
}
@SuppressWarnings("rawtypes")
public List selectList(String statement,
Object parameter,
Page page) {
return selectList(statement,
parameter,
page,
true);
}
@SuppressWarnings("rawtypes")
public List selectList(String statement,
Object parameter,
Page page,
boolean useCache) {
if (page != null) {
return selectList(statement,
parameter,
page.getFirstResult(),
page.getMaxResults(),
useCache);
} else {
return selectList(statement,
parameter,
0,
Integer.MAX_VALUE,
useCache);
}
}
@SuppressWarnings("rawtypes")
public List selectList(String statement,
ListQueryParameterObject parameter,
Page page) {
return selectList(statement,
parameter,
page,
true);
}
@SuppressWarnings("rawtypes")
public List selectList(String statement,
ListQueryParameterObject parameter,
Page page,
boolean useCache) {
ListQueryParameterObject parameterToUse = parameter;
if (parameterToUse == null) {
parameterToUse = new ListQueryParameterObject();
}
if (page != null) {
parameterToUse.setFirstResult(page.getFirstResult());
parameterToUse.setMaxResults(page.getMaxResults());
}
return selectList(statement,
parameterToUse,
useCache);
}
@SuppressWarnings("rawtypes")
public List selectList(String statement,
Object parameter,
int firstResult,
int maxResults) {
return selectList(statement,
parameter,
firstResult,
maxResults,
true);
}
@SuppressWarnings("rawtypes")
public List selectList(String statement,
Object parameter,
int firstResult,
int maxResults,
boolean useCache) {
return selectList(statement,
new ListQueryParameterObject(parameter,
firstResult,
maxResults),
useCache);
}
@SuppressWarnings("rawtypes")
public List selectList(String statement,
ListQueryParameterObject parameter) {
return selectList(statement,
parameter,
true);
}
@SuppressWarnings("rawtypes")
public List selectList(String statement,
ListQueryParameterObject parameter,
boolean useCache) {
return selectListWithRawParameter(statement,
parameter,
parameter.getFirstResult(),
parameter.getMaxResults(),
useCache);
}
@SuppressWarnings("rawtypes")
public List selectListWithRawParameter(String statement,
Object parameter,
int firstResult,
int maxResults) {
return selectListWithRawParameter(statement,
parameter,
firstResult,
maxResults,
true);
}
@SuppressWarnings({"rawtypes", "unchecked"})
public List selectListWithRawParameter(String statement,
Object parameter,
int firstResult,
int maxResults,
boolean useCache) {
statement = dbSqlSessionFactory.mapStatement(statement);
if (firstResult == -1 || maxResults == -1) {
return Collections.EMPTY_LIST;
}
List loadedObjects = sqlSession.selectList(statement,
parameter);
if (useCache) {
return cacheLoadOrStore(loadedObjects);
} else {
return loadedObjects;
}
}
@SuppressWarnings({"rawtypes"})
public List selectListWithRawParameterWithoutFilter(String statement,
Object parameter,
int firstResult,
int maxResults) {
statement = dbSqlSessionFactory.mapStatement(statement);
if (firstResult == -1 || maxResults == -1) {
return Collections.EMPTY_LIST;
}
return sqlSession.selectList(statement,
parameter);
}
public Object selectOne(String statement,
Object parameter) {
statement = dbSqlSessionFactory.mapStatement(statement);
Object result = sqlSession.selectOne(statement,
parameter);
if (result instanceof Entity) {
Entity loadedObject = (Entity) result;
result = cacheLoadOrStore(loadedObject);
}
return result;
}
public <T extends Entity> T selectById(Class<T> entityClass,
String id) {
return selectById(entityClass,
id,
true);
}
@SuppressWarnings("unchecked")
public <T extends Entity> T selectById(Class<T> entityClass,
String id,
boolean useCache) {
T entity = null;
if (useCache) {
entity = entityCache.findInCache(entityClass,
id);
if (entity != null) {
return entity;
}
}
String selectStatement = dbSqlSessionFactory.getSelectStatement(entityClass);
selectStatement = dbSqlSessionFactory.mapStatement(selectStatement);
entity = (T) sqlSession.selectOne(selectStatement,
id);
if (entity == null) {
return null;
}
entityCache.put(entity,
true); // true -> store state so we can see later if it is updated later on
return entity;
}
// internal session cache
// ///////////////////////////////////////////////////
@SuppressWarnings("rawtypes")
protected List cacheLoadOrStore(List<Object> loadedObjects) {
if (loadedObjects.isEmpty()) {
return loadedObjects;
}
if (!(loadedObjects.get(0) instanceof Entity)) {
return loadedObjects;
}
List<Entity> filteredObjects = new ArrayList<Entity>(loadedObjects.size());
for (Object loadedObject : loadedObjects) {
Entity cachedEntity = cacheLoadOrStore((Entity) loadedObject);
filteredObjects.add(cachedEntity);
}
return filteredObjects;
}
/**
* Returns the object in the cache. If this object was loaded before, then the original object is returned (the cached version is more recent).
* If this is the first time this object is loaded, then the loadedObject is added to the cache.
*/
protected Entity cacheLoadOrStore(Entity entity) {
Entity cachedEntity = entityCache.findInCache(entity.getClass(),
entity.getId());
if (cachedEntity != null) {
return cachedEntity;
}
entityCache.put(entity,
true);
return entity;
}
// flush
// ////////////////////////////////////////////////////////////////////
public void flush() {
determineUpdatedObjects(); // Needs to be done before the removeUnnecessaryOperations, as removeUnnecessaryOperations will remove stuff from the cache
removeUnnecessaryOperations();
if (log.isDebugEnabled()) {
debugFlush();
}
flushInserts();
flushUpdates();
flushDeletes();
}
/**
* Clears all deleted and inserted objects from the cache,
* and removes inserts and deletes that cancel each other.
* <p>
* Also removes deletes with duplicate ids.
*/
protected void removeUnnecessaryOperations() {
for (Class<? extends Entity> entityClass : deletedObjects.keySet()) {
// Collect ids of deleted entities + remove duplicates
Set<String> ids = new HashSet<String>();
Iterator<Entity> entitiesToDeleteIterator = deletedObjects.get(entityClass).values().iterator();
while (entitiesToDeleteIterator.hasNext()) {
Entity entityToDelete = entitiesToDeleteIterator.next();
if (!ids.contains(entityToDelete.getId())) {
ids.add(entityToDelete.getId());
} else {
entitiesToDeleteIterator.remove(); // Removing duplicate deletes
}
}
// Now we have the deleted ids, we can remove the inserted objects (as they cancel each other)
for (String id : ids) {
if (insertedObjects.containsKey(entityClass) && insertedObjects.get(entityClass).containsKey(id)) {
insertedObjects.get(entityClass).remove(id);
deletedObjects.get(entityClass).remove(id);
}
}
}
}
public void determineUpdatedObjects() {
updatedObjects = new ArrayList<Entity>();
Map<Class<?>, Map<String, CachedEntity>> cachedObjects = entityCache.getAllCachedEntities();
for (Class<?> clazz : cachedObjects.keySet()) {
Map<String, CachedEntity> classCache = cachedObjects.get(clazz);
for (CachedEntity cachedObject : classCache.values()) {
Entity cachedEntity = cachedObject.getEntity();
// Executions are stored as a hierarchical tree, and updates are important to execute
// even when the execution are deleted, as they can change the parent-child relationships.
// For the other entities, this is not applicable and an update can be discarded when an update follows.
if (!isEntityInserted(cachedEntity) &&
(ExecutionEntity.class.isAssignableFrom(cachedEntity.getClass()) || !isEntityToBeDeleted(cachedEntity)) &&
cachedObject.hasChanged()
) {
updatedObjects.add(cachedEntity);
}
}
}
}
protected void debugFlush() {
log.debug("Flushing dbSqlSession");
int nrOfInserts = 0, nrOfUpdates = 0, nrOfDeletes = 0;
for (Map<String, Entity> insertedObjectMap : insertedObjects.values()) {
for (Entity insertedObject : insertedObjectMap.values()) {
log.debug(" insert {}",
insertedObject);
nrOfInserts++;
}
}
for (Entity updatedObject : updatedObjects) {
log.debug(" update {}",
updatedObject);
nrOfUpdates++;
}
for (Map<String, Entity> deletedObjectMap : deletedObjects.values()) {
for (Entity deletedObject : deletedObjectMap.values()) {
log.debug(" delete {} with id {}",
deletedObject,
deletedObject.getId());
nrOfDeletes++;
}
}
for (Collection<BulkDeleteOperation> bulkDeleteOperationList : bulkDeleteOperations.values()) {
for (BulkDeleteOperation bulkDeleteOperation : bulkDeleteOperationList) {
log.debug(" {}",
bulkDeleteOperation);
nrOfDeletes++;
}
}
log.debug("flush summary: {} insert, {} update, {} delete.",
nrOfInserts,
nrOfUpdates,
nrOfDeletes);
log.debug("now executing flush...");
}
public boolean isEntityInserted(Entity entity) {
return insertedObjects.containsKey(entity.getClass())
&& insertedObjects.get(entity.getClass()).containsKey(entity.getId());
}
public boolean isEntityToBeDeleted(Entity entity) {
return deletedObjects.containsKey(entity.getClass())
&& deletedObjects.get(entity.getClass()).containsKey(entity.getId());
}
protected void flushInserts() {
if (insertedObjects.size() == 0) {
return;
}
// Handle in entity dependency order
for (Class<? extends Entity> entityClass : EntityDependencyOrder.INSERT_ORDER) {
if (insertedObjects.containsKey(entityClass)) {
flushInsertEntities(entityClass,
insertedObjects.get(entityClass).values());
insertedObjects.remove(entityClass);
}
}
// Next, in case of custom entities or we've screwed up and forgotten some entity
if (insertedObjects.size() > 0) {
for (Class<? extends Entity> entityClass : insertedObjects.keySet()) {
flushInsertEntities(entityClass,
insertedObjects.get(entityClass).values());
}
}
insertedObjects.clear();
}
protected void flushInsertEntities(Class<? extends Entity> entityClass,
Collection<Entity> entitiesToInsert) {
if (entitiesToInsert.size() == 1) {
flushRegularInsert(entitiesToInsert.iterator().next(),
entityClass);
} else if (Boolean.FALSE.equals(dbSqlSessionFactory.isBulkInsertable(entityClass))) {
for (Entity entity : entitiesToInsert) {
flushRegularInsert(entity,
entityClass);
}
} else {
flushBulkInsert(entitiesToInsert,
entityClass);
}
}
protected Collection<Entity> orderExecutionEntities(Map<String, Entity> executionEntities,
boolean parentBeforeChildExecution) {
// For insertion: parent executions should go before child executions
List<Entity> result = new ArrayList<Entity>(executionEntities.size());
// Gather parent-child relationships
Map<String, String> childToParentExecutionMapping = new HashMap<String, String>();
Map<String, List<ExecutionEntity>> parentToChildrenMapping = new HashMap<String, List<ExecutionEntity>>();
Collection<Entity> executionCollection = executionEntities.values();
Iterator<Entity> executionIterator = executionCollection.iterator();
while (executionIterator.hasNext()) {
ExecutionEntity currentExecutionEntity = (ExecutionEntity) executionIterator.next();
String parentId = currentExecutionEntity.getParentId();
String superExecutionId = currentExecutionEntity.getSuperExecutionId();
String parentKey = parentId != null ? parentId : superExecutionId;
childToParentExecutionMapping.put(currentExecutionEntity.getId(),
parentKey);
if (!parentToChildrenMapping.containsKey(parentKey)) {
parentToChildrenMapping.put(parentKey,
new ArrayList<ExecutionEntity>());
}
parentToChildrenMapping.get(parentKey).add(currentExecutionEntity);
}
// Loop over all entities, and insert in the correct order
Set<String> handledExecutionIds = new HashSet<String>(executionEntities.size());
executionIterator = executionCollection.iterator();
while (executionIterator.hasNext()) {
ExecutionEntity currentExecutionEntity = (ExecutionEntity) executionIterator.next();
String executionId = currentExecutionEntity.getId();
if (!handledExecutionIds.contains(executionId)) {
String parentId = childToParentExecutionMapping.get(executionId);
if (parentId != null) {
while (parentId != null) {
String newParentId = childToParentExecutionMapping.get(parentId);
if (newParentId == null) {
break;
}
parentId = newParentId;
}
}
if (parentId == null) {
parentId = executionId;
}
if (executionEntities.containsKey(parentId) && !handledExecutionIds.contains(parentId)) {
handledExecutionIds.add(parentId);
if (parentBeforeChildExecution) {
result.add(executionEntities.get(parentId));
} else {
result.add(0,
executionEntities.get(parentId));
}
}
collectChildExecutionsForInsertion(result,
parentToChildrenMapping,
handledExecutionIds,
parentId,
parentBeforeChildExecution);
}
}
return result;
}
protected void collectChildExecutionsForInsertion(List<Entity> result,
Map<String, List<ExecutionEntity>> parentToChildrenMapping,
Set<String> handledExecutionIds,
String parentId,
boolean parentBeforeChildExecution) {
List<ExecutionEntity> childExecutionEntities = parentToChildrenMapping.get(parentId);
if (childExecutionEntities == null) {
return;
}
for (ExecutionEntity childExecutionEntity : childExecutionEntities) {
handledExecutionIds.add(childExecutionEntity.getId());
if (parentBeforeChildExecution) {
result.add(childExecutionEntity);
} else {
result.add(0,
childExecutionEntity);
}
collectChildExecutionsForInsertion(result,
parentToChildrenMapping,
handledExecutionIds,
childExecutionEntity.getId(),
parentBeforeChildExecution);
}
}
protected void flushRegularInsert(Entity entity,
Class<? extends Entity> clazz) {
String insertStatement = dbSqlSessionFactory.getInsertStatement(entity);
insertStatement = dbSqlSessionFactory.mapStatement(insertStatement);
if (insertStatement == null) {
throw new ActivitiException("no insert statement for " + entity.getClass() + " in the ibatis mapping files");
}
log.debug("inserting: {}",
entity);
sqlSession.insert(insertStatement,
entity);
// See https://activiti.atlassian.net/browse/ACT-1290
if (entity instanceof HasRevision) {
incrementRevision(entity);
}
}
protected void flushBulkInsert(Collection<Entity> entities,
Class<? extends Entity> clazz) {
String insertStatement = dbSqlSessionFactory.getBulkInsertStatement(clazz);
insertStatement = dbSqlSessionFactory.mapStatement(insertStatement);
if (insertStatement == null) {
throw new ActivitiException("no insert statement for " + entities.iterator().next().getClass() + " in the ibatis mapping files");
}
Iterator<Entity> entityIterator = entities.iterator();
Boolean hasRevision = null;
while (entityIterator.hasNext()) {
List<Entity> subList = new ArrayList<Entity>();
int index = 0;
while (entityIterator.hasNext() && index < dbSqlSessionFactory.getMaxNrOfStatementsInBulkInsert()) {
Entity entity = entityIterator.next();
subList.add(entity);
if (hasRevision == null) {
hasRevision = entity instanceof HasRevision;
}
index++;
}
sqlSession.insert(insertStatement,
subList);
}
if (hasRevision != null && hasRevision) {
entityIterator = entities.iterator();
while (entityIterator.hasNext()) {
incrementRevision(entityIterator.next());
}
}
}
protected void incrementRevision(Entity insertedObject) {
HasRevision revisionEntity = (HasRevision) insertedObject;
if (revisionEntity.getRevision() == 0) {
revisionEntity.setRevision(revisionEntity.getRevisionNext());
}
}
protected void flushUpdates() {
for (Entity updatedObject : updatedObjects) {
String updateStatement = dbSqlSessionFactory.getUpdateStatement(updatedObject);
updateStatement = dbSqlSessionFactory.mapStatement(updateStatement);
if (updateStatement == null) {
throw new ActivitiException("no update statement for " + updatedObject.getClass() + " in the ibatis mapping files");
}
log.debug("updating: {}",
updatedObject);
int updatedRecords = sqlSession.update(updateStatement,
updatedObject);
if (updatedRecords == 0) {
throw new ActivitiOptimisticLockingException(updatedObject + " was updated by another transaction concurrently");
}
// See https://activiti.atlassian.net/browse/ACT-1290
if (updatedObject instanceof HasRevision) {
((HasRevision) updatedObject).setRevision(((HasRevision) updatedObject).getRevisionNext());
}
}
updatedObjects.clear();
}
protected void flushDeletes() {
if (deletedObjects.size() == 0 && bulkDeleteOperations.size() == 0) {
return;
}
// Handle in entity dependency order
for (Class<? extends Entity> entityClass : EntityDependencyOrder.DELETE_ORDER) {
if (deletedObjects.containsKey(entityClass)) {
flushDeleteEntities(entityClass,
deletedObjects.get(entityClass).values());
deletedObjects.remove(entityClass);
}
flushBulkDeletes(entityClass);
}
// Next, in case of custom entities or we've screwed up and forgotten some entity
if (deletedObjects.size() > 0) {
for (Class<? extends Entity> entityClass : deletedObjects.keySet()) {
flushDeleteEntities(entityClass,
deletedObjects.get(entityClass).values());
flushBulkDeletes(entityClass);
}
}
deletedObjects.clear();
}
protected void flushBulkDeletes(Class<? extends Entity> entityClass) {
// Bulk deletes
if (bulkDeleteOperations.containsKey(entityClass)) {
for (BulkDeleteOperation bulkDeleteOperation : bulkDeleteOperations.get(entityClass)) {
bulkDeleteOperation.execute(sqlSession);
}
}
}
protected void flushDeleteEntities(Class<? extends Entity> entityClass,
Collection<Entity> entitiesToDelete) {
for (Entity entity : entitiesToDelete) {
String deleteStatement = dbSqlSessionFactory.getDeleteStatement(entity.getClass());
deleteStatement = dbSqlSessionFactory.mapStatement(deleteStatement);
if (deleteStatement == null) {
throw new ActivitiException("no delete statement for " + entity.getClass() + " in the ibatis mapping files");
}
// It only makes sense to check for optimistic locking exceptions
// for objects that actually have a revision
if (entity instanceof HasRevision) {
int nrOfRowsDeleted = sqlSession.delete(deleteStatement,
entity);
if (nrOfRowsDeleted == 0) {
throw new ActivitiOptimisticLockingException(entity + " was updated by another transaction concurrently");
}
} else {
sqlSession.delete(deleteStatement,
entity);
}
}
}
public void close() {
sqlSession.close();
}
public void commit() {
sqlSession.commit();
}
public void rollback() {
sqlSession.rollback();
}
// schema operations
// ////////////////////////////////////////////////////////
public void dbSchemaCheckVersion() {
try {
String dbVersion = getDbVersion();
if (!ProcessEngine.VERSION.equals(dbVersion)) {
throw new ActivitiWrongDbException(ProcessEngine.VERSION,
dbVersion);
}
String errorMessage = null;
if (!isEngineTablePresent()) {
errorMessage = addMissingComponent(errorMessage,
"engine");
}
if (dbSqlSessionFactory.isDbHistoryUsed() && !isHistoryTablePresent()) {
errorMessage = addMissingComponent(errorMessage,
"history");
}
if (errorMessage != null) {
throw new ActivitiException("Activiti database problem: " + errorMessage);
}
} catch (Exception e) {
if (isMissingTablesException(e)) {
throw new ActivitiException(
"no activiti tables in db. set <property name=\"databaseSchemaUpdate\" to value=\"true\" or value=\"create-drop\" (use create-drop for testing only!) in bean processEngineConfiguration in activiti.cfg.xml for automatic schema creation",
e);
} else {
if (e instanceof RuntimeException) {
throw (RuntimeException) e;
} else {
throw new ActivitiException("couldn't get db schema version",
e);
}
}
}
log.debug("activiti db schema check successful");
}
protected String addMissingComponent(String missingComponents,
String component) {
if (missingComponents == null) {
return "Tables missing for component(s) " + component;
}
return missingComponents + ", " + component;
}
protected String getDbVersion() {
String selectSchemaVersionStatement = dbSqlSessionFactory.mapStatement("selectDbSchemaVersion");
return (String) sqlSession.selectOne(selectSchemaVersionStatement);
}
public void dbSchemaCreate() {
if (isEngineTablePresent()) {
String dbVersion = getDbVersion();
if (!ProcessEngine.VERSION.equals(dbVersion)) {
throw new ActivitiWrongDbException(ProcessEngine.VERSION,
dbVersion);
}
} else {
dbSchemaCreateEngine();
}