-
Notifications
You must be signed in to change notification settings - Fork 194
/
AbstractGrailsDomainBinder.java
3269 lines (2806 loc) · 138 KB
/
AbstractGrailsDomainBinder.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
/* Copyright 2004-2005 the original author or authors.
*
* 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.grails.orm.hibernate.cfg;
import groovy.lang.Closure;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codehaus.groovy.runtime.DefaultGroovyMethods;
import org.grails.datastore.mapping.model.*;
import org.grails.datastore.mapping.model.config.GormProperties;
import org.grails.datastore.mapping.model.types.*;
import org.grails.datastore.mapping.model.types.ToOne;
import org.grails.datastore.mapping.reflect.NameUtils;
import org.hibernate.FetchMode;
import org.hibernate.MappingException;
import org.hibernate.cfg.*;
import org.hibernate.id.PersistentIdentifierGenerator;
import org.hibernate.mapping.*;
import org.hibernate.mapping.Collection;
import org.hibernate.mapping.ManyToOne;
import org.hibernate.mapping.OneToMany;
import org.hibernate.mapping.OneToOne;
import org.hibernate.mapping.Table;
import org.hibernate.persister.entity.UnionSubclassEntityPersister;
import org.hibernate.type.*;
import org.springframework.util.StringUtils;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.Types;
import java.util.*;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Handles the binding Grails domain classes and properties to the Hibernate runtime meta model.
* Based on the HbmBinder code in Hibernate core and influenced by AnnotationsBinder.
*
* @author Graeme Rocher
* @since 0.1
*/
public abstract class AbstractGrailsDomainBinder {
protected static final String CASCADE_ALL_DELETE_ORPHAN = "all-delete-orphan";
protected static final String FOREIGN_KEY_SUFFIX = "_id";
protected static final String STRING_TYPE = "string";
protected static final String EMPTY_PATH = "";
protected static final char UNDERSCORE = '_';
protected static final String CASCADE_ALL = "all";
protected static final String CASCADE_SAVE_UPDATE = "save-update";
protected static final String CASCADE_NONE = "none";
protected static final String BACKTICK = "`";
protected static final Map<Class<?>, Mapping> MAPPING_CACHE = new HashMap<Class<?>, Mapping>();
protected static final String ENUM_TYPE_CLASS = "org.hibernate.type.EnumType";
protected static final String ENUM_CLASS_PROP = "enumClass";
protected static final String ENUM_TYPE_PROP = "type";
protected static final String DEFAULT_ENUM_TYPE = "default";
protected Log LOG = LogFactory.getLog(getClass());
protected Closure defaultMapping;
protected final CollectionType CT = new CollectionType(null, this) {
public Collection create(ToMany property, PersistentClass owner, String path, Mappings mappings, String sessionFactoryBeanName) {
return null;
}
};
/**
* Overrideable naming strategy. Defaults to <code>ImprovedNamingStrategy</code> but can
* be configured in DataSource.groovy via <code>hibernate.naming_strategy = ...</code>.
*/
public static Map<String, NamingStrategy> NAMING_STRATEGIES = new HashMap<String, NamingStrategy>();
static {
NAMING_STRATEGIES.put(Mapping.DEFAULT_DATA_SOURCE, ImprovedNamingStrategy.INSTANCE);
}
private PersistentEntityNamingStrategy namingStrategy;
/**
* The default ORM mapping
*
* @param defaultMapping The default mapping
*/
public void setDefaultMapping(Closure defaultMapping) {
this.defaultMapping = defaultMapping;
}
/**
*
* @param namingStrategy Custom naming strategy to plugin into table naming
*/
public void setNamingStrategy(PersistentEntityNamingStrategy namingStrategy) {
this.namingStrategy = namingStrategy;
}
/**
* Second pass class for grails relationships. This is required as all
* persistent classes need to be loaded in the first pass and then relationships
* established in the second pass compile
*
* @author Graeme
*/
class GrailsCollectionSecondPass implements SecondPass {
private static final long serialVersionUID = -5540526942092611348L;
protected ToMany property;
protected Mappings mappings;
protected Collection collection;
protected String sessionFactoryBeanName;
public GrailsCollectionSecondPass(ToMany property, Mappings mappings,
Collection coll, String sessionFactoryBeanName) {
this.property = property;
this.mappings = mappings;
this.collection = coll;
this.sessionFactoryBeanName = sessionFactoryBeanName;
}
public void doSecondPass(Map<?, ?> persistentClasses, Map<?, ?> inheritedMetas) throws MappingException {
bindCollectionSecondPass(property, mappings, persistentClasses, collection, sessionFactoryBeanName);
createCollectionKeys();
}
protected void createCollectionKeys() {
collection.createAllKeys();
if (LOG.isDebugEnabled()) {
String msg = "Mapped collection key: " + columns(collection.getKey());
if (collection.isIndexed())
msg += ", index: " + columns(((IndexedCollection) collection).getIndex());
if (collection.isOneToMany()) {
msg += ", one-to-many: "
+ ((OneToMany) collection.getElement()).getReferencedEntityName();
} else {
msg += ", element: " + columns(collection.getElement());
}
LOG.debug(msg);
}
}
protected String columns(Value val) {
StringBuilder columns = new StringBuilder();
Iterator<?> iter = val.getColumnIterator();
while (iter.hasNext()) {
columns.append(((Selectable) iter.next()).getText());
if (iter.hasNext()) columns.append(", ");
}
return columns.toString();
}
@SuppressWarnings("rawtypes")
public void doSecondPass(Map persistentClasses) throws MappingException {
bindCollectionSecondPass(property, mappings, persistentClasses, collection, sessionFactoryBeanName);
createCollectionKeys();
}
}
class ListSecondPass extends GrailsCollectionSecondPass {
private static final long serialVersionUID = -3024674993774205193L;
public ListSecondPass(ToMany property, Mappings mappings,
Collection coll, String sessionFactoryBeanName) {
super(property, mappings, coll, sessionFactoryBeanName);
}
@Override
public void doSecondPass(Map<?, ?> persistentClasses, Map<?, ?> inheritedMetas) throws MappingException {
bindListSecondPass(property, mappings, persistentClasses,
(org.hibernate.mapping.List) collection, sessionFactoryBeanName);
}
@SuppressWarnings("rawtypes")
@Override
public void doSecondPass(Map persistentClasses) throws MappingException {
bindListSecondPass(property, mappings, persistentClasses,
(org.hibernate.mapping.List) collection, sessionFactoryBeanName);
}
}
class MapSecondPass extends GrailsCollectionSecondPass {
private static final long serialVersionUID = -3244991685626409031L;
public MapSecondPass(ToMany property, Mappings mappings,
Collection coll, String sessionFactoryBeanName) {
super(property, mappings, coll, sessionFactoryBeanName);
}
@Override
public void doSecondPass(Map<?, ?> persistentClasses, Map<?, ?> inheritedMetas) throws MappingException {
bindMapSecondPass(property, mappings, persistentClasses,
(org.hibernate.mapping.Map)collection, sessionFactoryBeanName);
}
@SuppressWarnings("rawtypes")
@Override
public void doSecondPass(Map persistentClasses) throws MappingException {
bindMapSecondPass(property, mappings, persistentClasses,
(org.hibernate.mapping.Map) collection, sessionFactoryBeanName);
}
}
/**
* Override the default naming strategy for the default datasource given a Class or a full class name.
* @param strategy the class or name
* @throws ClassNotFoundException
* @throws InstantiationException
* @throws IllegalAccessException
*/
public static void configureNamingStrategy(final Object strategy) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
configureNamingStrategy(Mapping.DEFAULT_DATA_SOURCE, strategy);
}
/**
* Override the default naming strategy given a Class or a full class name,
* or an instance of a NamingStrategy.
*
* @param datasourceName the datasource name
* @param strategy the class, name, or instance
* @throws ClassNotFoundException
* @throws InstantiationException
* @throws IllegalAccessException
*/
public static void configureNamingStrategy(final String datasourceName, final Object strategy) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
Class<?> namingStrategyClass = null;
NamingStrategy namingStrategy;
if (strategy instanceof Class<?>) {
namingStrategyClass = (Class<?>)strategy;
}
else if (strategy instanceof CharSequence) {
namingStrategyClass = Thread.currentThread().getContextClassLoader().loadClass(strategy.toString());
}
if (namingStrategyClass == null) {
namingStrategy = (NamingStrategy)strategy;
}
else {
namingStrategy = (NamingStrategy)namingStrategyClass.newInstance();
}
NAMING_STRATEGIES.put(datasourceName, namingStrategy);
}
protected void bindMapSecondPass(ToMany property, Mappings mappings,
Map<?, ?> persistentClasses, org.hibernate.mapping.Map map, String sessionFactoryBeanName) {
bindCollectionSecondPass(property, mappings, persistentClasses, map, sessionFactoryBeanName);
SimpleValue value = new SimpleValue(mappings, map.getCollectionTable());
bindSimpleValue(getIndexColumnType(property, STRING_TYPE), value, true,
getIndexColumnName(property, sessionFactoryBeanName), mappings);
PropertyConfig pc = getPropertyConfig(property);
if (pc != null && pc.getIndexColumn() != null) {
bindColumnConfigToColumn(property, getColumnForSimpleValue(value), getSingleColumnConfig(pc.getIndexColumn()));
}
if (!value.isTypeSpecified()) {
throw new MappingException("map index element must specify a type: " + map.getRole());
}
map.setIndex(value);
if(!(property instanceof org.grails.datastore.mapping.model.types.OneToMany) && !(property instanceof ManyToMany)) {
SimpleValue elt = new SimpleValue(mappings, map.getCollectionTable());
map.setElement(elt);
String typeName = getTypeName(property,getPropertyConfig(property), getMapping(property.getOwner()));
if (typeName == null ) {
if(property instanceof Basic) {
Basic basic = (Basic) property;
typeName = basic.getComponentType().getName();
}
}
if(typeName == null || typeName.equals(Object.class.getName())) {
typeName = StandardBasicTypes.STRING.getName();
}
bindSimpleValue(typeName, elt, false, getMapElementName(property, sessionFactoryBeanName), mappings);
elt.setTypeName(typeName);
}
map.setInverse(false);
}
protected ColumnConfig getSingleColumnConfig(PropertyConfig propertyConfig) {
if (propertyConfig != null) {
List<ColumnConfig> columns = propertyConfig.getColumns();
if (columns != null && !columns.isEmpty()) {
return columns.get(0);
}
}
return null;
}
protected void bindListSecondPass(ToMany property, Mappings mappings,
Map<?, ?> persistentClasses, org.hibernate.mapping.List list, String sessionFactoryBeanName) {
bindCollectionSecondPass(property, mappings, persistentClasses, list, sessionFactoryBeanName);
String columnName = getIndexColumnName(property, sessionFactoryBeanName);
final boolean isManyToMany = property instanceof ManyToMany;
if (isManyToMany && !property.isOwningSide()) {
throw new MappingException("Invalid association [" + property +
"]. List collection types only supported on the owning side of a many-to-many relationship.");
}
Table collectionTable = list.getCollectionTable();
SimpleValue iv = new SimpleValue(mappings, collectionTable);
bindSimpleValue("integer", iv, true, columnName, mappings);
iv.setTypeName("integer");
list.setIndex(iv);
list.setBaseIndex(0);
list.setInverse(false);
Value v = list.getElement();
v.createForeignKey();
if (property.isBidirectional()) {
String entityName;
Value element = list.getElement();
if (element instanceof ManyToOne) {
ManyToOne manyToOne = (ManyToOne) element;
entityName = manyToOne.getReferencedEntityName();
} else {
entityName = ((OneToMany) element).getReferencedEntityName();
}
PersistentClass referenced = mappings.getClass(entityName);
Class<?> mappedClass = referenced.getMappedClass();
Mapping m = getMapping(mappedClass);
boolean compositeIdProperty = isCompositeIdProperty(m, property.getInverseSide());
if (!compositeIdProperty) {
Backref prop = new Backref();
final PersistentEntity owner = property.getOwner();
prop.setEntityName(owner.getName());
prop.setName(UNDERSCORE + addUnderscore(owner.getJavaClass().getSimpleName(), property.getName()) + "Backref");
prop.setSelectable(false);
prop.setUpdateable(false);
if (isManyToMany) {
prop.setInsertable(false);
}
prop.setCollectionRole(list.getRole());
prop.setValue(list.getKey());
DependantValue value = (DependantValue) prop.getValue();
if (!property.isCircular()) {
value.setNullable(false);
}
value.setUpdateable(true);
prop.setOptional(false);
referenced.addProperty(prop);
}
if ((!list.getKey().isNullable() && !list.isInverse()) || compositeIdProperty) {
IndexBackref ib = new IndexBackref();
ib.setName(UNDERSCORE + property.getName() + "IndexBackref");
ib.setUpdateable(false);
ib.setSelectable(false);
if (isManyToMany) {
ib.setInsertable(false);
}
ib.setCollectionRole(list.getRole());
ib.setEntityName(list.getOwner().getEntityName());
ib.setValue(list.getIndex());
referenced.addProperty(ib);
}
}
}
protected void bindCollectionSecondPass(ToMany property, Mappings mappings,
Map<?, ?> persistentClasses, Collection collection, String sessionFactoryBeanName) {
PersistentClass associatedClass = null;
if (LOG.isDebugEnabled())
LOG.debug("Mapping collection: "
+ collection.getRole()
+ " -> "
+ collection.getCollectionTable().getName());
PropertyConfig propConfig = getPropertyConfig(property);
if (propConfig != null && StringUtils.hasText(propConfig.getSort())) {
if (!property.isBidirectional() && (property instanceof org.grails.datastore.mapping.model.types.OneToMany)) {
throw new DatastoreConfigurationException("Default sort for associations ["+property.getOwner().getName()+"->" + property.getName() +
"] are not supported with unidirectional one to many relationships.");
}
PersistentEntity referenced = property.getAssociatedEntity();
if (referenced != null) {
PersistentProperty propertyToSortBy = referenced.getPropertyByName(propConfig.getSort());
String associatedClassName = property.getAssociatedEntity().getName();
associatedClass = (PersistentClass) persistentClasses.get(associatedClassName);
if (associatedClass != null) {
collection.setOrderBy(buildOrderByClause(propertyToSortBy.getName(), associatedClass, collection.getRole(),
propConfig.getOrder() != null ? propConfig.getOrder() : "asc"));
}
}
}
// Configure one-to-many
if (collection.isOneToMany()) {
PersistentEntity referenced = property.getAssociatedEntity();
Mapping m = getRootMapping(referenced);
boolean tablePerSubclass = m != null && !m.getTablePerHierarchy();
if (referenced != null && !referenced.isRoot() && !tablePerSubclass) {
Mapping rootMapping = getRootMapping(referenced);
String discriminatorColumnName = RootClass.DEFAULT_DISCRIMINATOR_COLUMN_NAME;
if (rootMapping != null) {
final ColumnConfig discriminatorColumn = rootMapping.getDiscriminatorColumn();
if (discriminatorColumn != null) {
discriminatorColumnName = discriminatorColumn.getName();
}
if (rootMapping.getDiscriminatorMap().get("formula") != null) {
discriminatorColumnName = (String)m.getDiscriminatorMap().get("formula");
}
}
//NOTE: this will build the set for the in clause if it has sublcasses
Set<String> discSet = buildDiscriminatorSet((HibernatePersistentEntity) referenced);
String inclause = DefaultGroovyMethods.join(discSet, ",");
collection.setWhere(discriminatorColumnName + " in (" + inclause + ")");
}
OneToMany oneToMany = (OneToMany) collection.getElement();
String associatedClassName = oneToMany.getReferencedEntityName();
associatedClass = (PersistentClass) persistentClasses.get(associatedClassName);
// if there is no persistent class for the association throw exception
if (associatedClass == null) {
throw new MappingException("Association references unmapped class: " + oneToMany.getReferencedEntityName());
}
oneToMany.setAssociatedClass(associatedClass);
if (shouldBindCollectionWithForeignKey(property)) {
collection.setCollectionTable(associatedClass.getTable());
}
bindCollectionForPropertyConfig(collection, propConfig);
}
if (isSorted(property)) {
collection.setSorted(true);
}
// setup the primary key references
DependantValue key = createPrimaryKeyValue(mappings, property, collection, persistentClasses);
// link a bidirectional relationship
if (property.isBidirectional()) {
Association otherSide = property.getInverseSide();
if ((otherSide instanceof org.grails.datastore.mapping.model.types.ToOne) && shouldBindCollectionWithForeignKey(property)) {
linkBidirectionalOneToMany(collection, associatedClass, key, otherSide);
} else if ((otherSide instanceof ManyToMany) || Map.class.isAssignableFrom(property.getType())) {
bindDependentKeyValue(property, key, mappings, sessionFactoryBeanName);
}
} else {
if (hasJoinKeyMapping(propConfig)) {
bindSimpleValue("long", key,false, propConfig.getJoinTable().getKey().getName(), mappings);
} else {
bindDependentKeyValue(property, key, mappings, sessionFactoryBeanName);
}
}
collection.setKey(key);
// get cache config
if (propConfig != null) {
CacheConfig cacheConfig = propConfig.getCache();
if (cacheConfig != null) {
collection.setCacheConcurrencyStrategy(cacheConfig.getUsage());
}
}
// if we have a many-to-many
final boolean isManyToMany = property instanceof ManyToMany;
if (isManyToMany || isBidirectionalOneToManyMap(property)) {
PersistentProperty otherSide = property.getInverseSide();
if (property.isBidirectional()) {
if (LOG.isDebugEnabled())
LOG.debug("[GrailsDomainBinder] Mapping other side " + otherSide.getOwner().getName() + "." + otherSide.getName() + " -> " + collection.getCollectionTable().getName() + " as ManyToOne");
ManyToOne element = new ManyToOne(mappings, collection.getCollectionTable());
bindManyToMany((Association)otherSide, element, mappings, sessionFactoryBeanName);
collection.setElement(element);
bindCollectionForPropertyConfig(collection, propConfig);
if (property.isCircular()) {
collection.setInverse(false);
}
} else {
// TODO support unidirectional many-to-many
}
} else if (shouldCollectionBindWithJoinColumn(property)) {
bindCollectionWithJoinTable(property, mappings, collection, propConfig, sessionFactoryBeanName);
} else if (isUnidirectionalOneToMany(property)) {
// for non-inverse one-to-many, with a not-null fk, add a backref!
// there are problems with list and map mappings and join columns relating to duplicate key constraints
// TODO change this when HHH-1268 is resolved
bindUnidirectionalOneToMany((org.grails.datastore.mapping.model.types.OneToMany) property, mappings, collection);
}
}
@SuppressWarnings("unchecked")
protected String buildOrderByClause(String hqlOrderBy, PersistentClass associatedClass, String role, String defaultOrder) {
String orderByString = null;
if (hqlOrderBy != null) {
List<String> properties = new ArrayList<String>();
List<String> ordering = new ArrayList<String>();
StringBuilder orderByBuffer = new StringBuilder();
if (hqlOrderBy.length() == 0) {
//order by id
Iterator<?> it = associatedClass.getIdentifier().getColumnIterator();
while (it.hasNext()) {
Selectable col = (Selectable) it.next();
orderByBuffer.append(col.getText()).append(" asc").append(", ");
}
}
else {
StringTokenizer st = new StringTokenizer(hqlOrderBy, " ,", false);
String currentOrdering = defaultOrder;
//FIXME make this code decent
while (st.hasMoreTokens()) {
String token = st.nextToken();
if (isNonPropertyToken(token)) {
if (currentOrdering != null) {
throw new DatastoreConfigurationException(
"Error while parsing sort clause: " + hqlOrderBy
+ " (" + role + ")"
);
}
currentOrdering = token;
}
else {
//Add ordering of the previous
if (currentOrdering == null) {
//default ordering
ordering.add("asc");
}
else {
ordering.add(currentOrdering);
currentOrdering = null;
}
properties.add(token);
}
}
ordering.remove(0); //first one is the algorithm starter
// add last one ordering
if (currentOrdering == null) {
//default ordering
ordering.add(defaultOrder);
}
else {
ordering.add(currentOrdering);
currentOrdering = null;
}
int index = 0;
for (String property : properties) {
Property p = BinderHelper.findPropertyByName(associatedClass, property);
if (p == null) {
throw new DatastoreConfigurationException(
"property from sort clause not found: "
+ associatedClass.getEntityName() + "." + property
);
}
PersistentClass pc = p.getPersistentClass();
String table;
if (pc == null) {
table = "";
}
else if (pc == associatedClass
|| (associatedClass instanceof SingleTableSubclass &&
pc.getMappedClass().isAssignableFrom(associatedClass.getMappedClass()))) {
table = "";
} else {
table = pc.getTable().getQuotedName() + ".";
}
Iterator<?> propertyColumns = p.getColumnIterator();
while (propertyColumns.hasNext()) {
Selectable column = (Selectable) propertyColumns.next();
orderByBuffer.append(table)
.append(column.getText())
.append(" ")
.append(ordering.get(index))
.append(", ");
}
index++;
}
}
orderByString = orderByBuffer.substring(0, orderByBuffer.length() - 2);
}
return orderByString;
}
protected boolean isNonPropertyToken(String token) {
if (" ".equals(token)) return true;
if (",".equals(token)) return true;
if (token.equalsIgnoreCase("desc")) return true;
if (token.equalsIgnoreCase("asc")) return true;
return false;
}
protected Set<String> buildDiscriminatorSet(HibernatePersistentEntity domainClass) {
Set<String> theSet = new HashSet<String>();
Mapping mapping = domainClass.getMapping().getMappedForm();
String discriminator = domainClass.getName();
if (mapping != null && mapping.getDiscriminator() != null) {
discriminator = mapping.getDiscriminator();
}
Mapping rootMapping = getRootMapping(domainClass);
String quote = "'";
if (rootMapping != null && rootMapping.getDiscriminatorMap() != null &&
rootMapping.getDiscriminatorMap().get("type") != null && rootMapping.getDiscriminatorMap().get("type") != "string") {
quote = "";
}
theSet.add(quote + discriminator + quote);
final java.util.Collection<PersistentEntity> childEntities = domainClass.getMappingContext().getDirectChildEntities(domainClass);
for (PersistentEntity subClass : childEntities) {
theSet.addAll(buildDiscriminatorSet((HibernatePersistentEntity) subClass));
}
return theSet;
}
protected Mapping getRootMapping(PersistentEntity referenced) {
if (referenced == null) return null;
Class<?> current = referenced.getJavaClass();
while (true) {
Class<?> superClass = current.getSuperclass();
if (Object.class.equals(superClass)) break;
current = superClass;
}
return getMapping(current);
}
protected boolean isBidirectionalOneToManyMap(Association property) {
return Map.class.isAssignableFrom(property.getType()) && property.isBidirectional();
}
protected void bindCollectionWithJoinTable(ToMany property,
Mappings mappings, Collection collection, PropertyConfig config, String sessionFactoryBeanName) {
NamingStrategy namingStrategy = getNamingStrategy(sessionFactoryBeanName);
SimpleValue element;
final boolean isBasicCollectionType = property instanceof Basic;
if (isBasicCollectionType) {
element = new SimpleValue(mappings, collection.getCollectionTable());
}
else {
// for a normal unidirectional one-to-many we use a join column
element = new ManyToOne(mappings, collection.getCollectionTable());
bindUnidirectionalOneToManyInverseValues(property, (ManyToOne) element);
}
collection.setInverse(false);
String columnName;
final boolean hasJoinColumnMapping = hasJoinColumnMapping(config);
if (isBasicCollectionType) {
final Class<?> referencedType = ((Basic)property).getComponentType();
String className = referencedType.getName();
final boolean isEnum = referencedType.isEnum();
if (hasJoinColumnMapping) {
columnName = config.getJoinTable().getColumn().getName();
}
else {
columnName = isEnum ? namingStrategy.propertyToColumnName(className) :
addUnderscore(namingStrategy.propertyToColumnName(property.getName()),
namingStrategy.propertyToColumnName(className));
}
if (isEnum) {
bindEnumType(property, referencedType,element,columnName);
}
else {
String typeName = getTypeName(property, config, getMapping(property.getOwner()));
if (typeName == null) {
Type type = mappings.getTypeResolver().basic(className);
if (type != null) {
typeName = type.getName();
}
}
if (typeName == null) {
String domainName = property.getOwner().getName();
throw new MappingException("Missing type or column for column["+columnName+"] on domain["+domainName+"] referencing["+className+"]");
}
bindSimpleValue(typeName, element,true, columnName, mappings);
if (hasJoinColumnMapping) {
bindColumnConfigToColumn(property, getColumnForSimpleValue(element), config.getJoinTable().getColumn());
}
}
} else {
final PersistentEntity domainClass = property.getAssociatedEntity();
Mapping m = getMapping(domainClass);
if (hasCompositeIdentifier(m)) {
CompositeIdentity ci = (CompositeIdentity) m.getIdentity();
bindCompositeIdentifierToManyToOne(property, element, ci, domainClass,
EMPTY_PATH, sessionFactoryBeanName);
}
else {
if (hasJoinColumnMapping) {
columnName = config.getJoinTable().getColumn().getName();
}
else {
columnName = namingStrategy.propertyToColumnName(NameUtils.decapitalize(domainClass.getName())) + FOREIGN_KEY_SUFFIX;
}
bindSimpleValue("long", element,true, columnName, mappings);
}
}
collection.setElement(element);
bindCollectionForPropertyConfig(collection, config);
}
protected String addUnderscore(String s1, String s2) {
return removeBackticks(s1) + UNDERSCORE + removeBackticks(s2);
}
protected String removeBackticks(String s) {
return s.startsWith("`") && s.endsWith("`") ? s.substring(1, s.length() - 1) : s;
}
protected Column getColumnForSimpleValue(SimpleValue element) {
return (Column)element.getColumnIterator().next();
}
protected String getTypeName(PersistentProperty property, PropertyConfig config, Mapping mapping) {
if (config != null && config.getType() != null) {
final Object typeObj = config.getType();
if (typeObj instanceof Class<?>) {
return ((Class<?>)typeObj).getName();
}
return typeObj.toString();
}
if (mapping != null) {
return mapping.getTypeName(property.getType());
}
return null;
}
protected void bindColumnConfigToColumn(PersistentProperty property, Column column, ColumnConfig columnConfig) {
final PropertyConfig mappedForm = property != null ? (PropertyConfig) property.getMapping().getMappedForm() : null;
boolean allowUnique = mappedForm != null && !mappedForm.isUniqueWithinGroup();
if (columnConfig == null) {
return;
}
if (columnConfig.getLength() != -1) {
column.setLength(columnConfig.getLength());
}
if (columnConfig.getPrecision() != -1) {
column.setPrecision(columnConfig.getPrecision());
}
if (columnConfig.getScale() != -1) {
column.setScale(columnConfig.getScale());
}
if (columnConfig.getSqlType() != null && !columnConfig.getSqlType().isEmpty()) {
column.setSqlType(columnConfig.getSqlType());
}
if(allowUnique) {
column.setUnique(columnConfig.getUnique());
}
}
protected boolean hasJoinColumnMapping(PropertyConfig config) {
return config != null && config.getJoinTable() != null && config.getJoinTable().getColumn() != null;
}
protected boolean shouldCollectionBindWithJoinColumn(ToMany property) {
PropertyConfig config = getPropertyConfig(property);
JoinTable jt = config != null ? config.getJoinTable() : new JoinTable();
return (isUnidirectionalOneToMany(property) || (property instanceof Basic)) && jt != null;
}
/**
* @param property
* @param manyToOne
*/
protected void bindUnidirectionalOneToManyInverseValues(ToMany property, ManyToOne manyToOne) {
PropertyConfig config = getPropertyConfig(property);
if (config == null) {
manyToOne.setLazy(true);
} else {
manyToOne.setIgnoreNotFound(config.getIgnoreNotFound());
final FetchMode fetch = config.getFetch();
if(!fetch.equals(FetchMode.JOIN) && !fetch.equals(FetchMode.EAGER)) {
manyToOne.setLazy(true);
}
final Boolean lazy = config.getLazy();
if(lazy != null) {
manyToOne.setLazy(lazy);
}
}
// set referenced entity
manyToOne.setReferencedEntityName(property.getAssociatedEntity().getName());
}
protected void bindCollectionForPropertyConfig(Collection collection, PropertyConfig config) {
if (config == null) {
collection.setLazy(true);
collection.setExtraLazy(false);
} else {
final FetchMode fetch = config.getFetch();
if(!fetch.equals(FetchMode.JOIN) && !fetch.equals(FetchMode.EAGER)) {
collection.setLazy(true);
}
final Boolean lazy = config.getLazy();
if(lazy != null) {
collection.setExtraLazy(lazy);
}
}
}
public PropertyConfig getPropertyConfig(PersistentProperty property) {
return (PropertyConfig) property.getMapping().getMappedForm();
}
/**
* Checks whether a property is a unidirectional non-circular one-to-many
*
* @param property The property to check
* @return true if it is unidirectional and a one-to-many
*/
protected boolean isUnidirectionalOneToMany(PersistentProperty property) {
return ((property instanceof org.grails.datastore.mapping.model.types.OneToMany) && !((Association)property).isBidirectional());
}
/**
* Binds the primary key value column
*
* @param property The property
* @param key The key
* @param mappings The mappings
*/
protected void bindDependentKeyValue(PersistentProperty property, DependantValue key,
Mappings mappings, String sessionFactoryBeanName) {
if (LOG.isDebugEnabled()) {
LOG.debug("[GrailsDomainBinder] binding [" + property.getName() + "] with dependant key");
}
PersistentEntity refDomainClass = property.getOwner();
final Mapping mapping = getMapping(refDomainClass.getJavaClass());
boolean hasCompositeIdentifier = hasCompositeIdentifier(mapping);
if ((shouldCollectionBindWithJoinColumn((ToMany) property) && hasCompositeIdentifier) ||
(hasCompositeIdentifier && ( property instanceof ManyToMany))) {
CompositeIdentity ci = (CompositeIdentity) mapping.getIdentity();
bindCompositeIdentifierToManyToOne((Association) property, key, ci, refDomainClass, EMPTY_PATH, sessionFactoryBeanName);
}
else {
bindSimpleValue(property, null, key, EMPTY_PATH, mappings, sessionFactoryBeanName);
}
}
/**
* Creates the DependentValue object that forms a primary key reference for the collection.
*
* @param mappings
* @param property The grails property
* @param collection The collection object
* @param persistentClasses
* @return The DependantValue (key)
*/
protected DependantValue createPrimaryKeyValue(Mappings mappings, PersistentProperty property,
Collection collection, Map<?, ?> persistentClasses) {
KeyValue keyValue;
DependantValue key;
String propertyRef = collection.getReferencedPropertyName();
// this is to support mapping by a property
if (propertyRef == null) {
keyValue = collection.getOwner().getIdentifier();
} else {
keyValue = (KeyValue) collection.getOwner().getProperty(propertyRef).getValue();
}
if (LOG.isDebugEnabled())
LOG.debug("[GrailsDomainBinder] creating dependant key value to table [" + keyValue.getTable().getName() + "]");
key = new DependantValue(mappings, collection.getCollectionTable(), keyValue);
key.setTypeName(null);
// make nullable and non-updateable
key.setNullable(true);
key.setUpdateable(false);
return key;
}
/**
* Binds a unidirectional one-to-many creating a psuedo back reference property in the process.
*
* @param property
* @param mappings
* @param collection
*/
protected void bindUnidirectionalOneToMany(org.grails.datastore.mapping.model.types.OneToMany property, Mappings mappings, Collection collection) {
Value v = collection.getElement();
v.createForeignKey();
String entityName;
if (v instanceof ManyToOne) {
ManyToOne manyToOne = (ManyToOne) v;
entityName = manyToOne.getReferencedEntityName();
} else {
entityName = ((OneToMany) v).getReferencedEntityName();
}
collection.setInverse(false);
PersistentClass referenced = mappings.getClass(entityName);
Backref prop = new Backref();
PersistentEntity owner = property.getOwner();
prop.setEntityName(owner.getName());
prop.setName(UNDERSCORE + addUnderscore(owner.getJavaClass().getSimpleName(), property.getName()) + "Backref");
prop.setUpdateable(false);
prop.setInsertable(true);
prop.setCollectionRole(collection.getRole());
prop.setValue(collection.getKey());
prop.setOptional(true);
referenced.addProperty(prop);
}
protected Property getProperty(PersistentClass associatedClass, String propertyName) throws MappingException {
try {
return associatedClass.getProperty(propertyName);
}
catch (MappingException e) {
//maybe it's squirreled away in a composite primary key
if (associatedClass.getKey() instanceof Component) {
return ((Component) associatedClass.getKey()).getProperty(propertyName);
}
throw e;
}
}
/**
* Links a bidirectional one-to-many, configuring the inverse side and using a column copy to perform the link
*
* @param collection The collection one-to-many
* @param associatedClass The associated class
* @param key The key
* @param otherSide The other side of the relationship
*/
protected void linkBidirectionalOneToMany(Collection collection, PersistentClass associatedClass, DependantValue key, PersistentProperty otherSide) {
collection.setInverse(true);
// Iterator mappedByColumns = associatedClass.getProperty(otherSide.getName()).getValue().getColumnIterator();
Iterator<?> mappedByColumns = getProperty(associatedClass, otherSide.getName()).getValue().getColumnIterator();
while (mappedByColumns.hasNext()) {
Column column = (Column) mappedByColumns.next();
linkValueUsingAColumnCopy(otherSide, column, key);
}
}
/**
* Establish whether a collection property is sorted
*