-
Notifications
You must be signed in to change notification settings - Fork 3.5k
/
EntityType.java
727 lines (655 loc) · 21.5 KB
/
EntityType.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
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2010, Red Hat Inc. or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Inc.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.type;
import java.io.Serializable;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;
import org.dom4j.Element;
import org.dom4j.Node;
import org.hibernate.AssertionFailure;
import org.hibernate.EntityMode;
import org.hibernate.HibernateException;
import org.hibernate.MappingException;
import org.hibernate.engine.internal.ForeignKeys;
import org.hibernate.engine.spi.EntityUniqueKey;
import org.hibernate.engine.spi.Mapping;
import org.hibernate.engine.spi.PersistenceContext;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.internal.util.ReflectHelper;
import org.hibernate.persister.entity.EntityPersister;
import org.hibernate.persister.entity.Joinable;
import org.hibernate.persister.entity.UniqueKeyLoadable;
import org.hibernate.proxy.HibernateProxy;
import org.hibernate.tuple.ElementWrapper;
/**
* Base for types which map associations to persistent entities.
*
* @author Gavin King
*/
public abstract class EntityType extends AbstractType implements AssociationType {
private final TypeFactory.TypeScope scope;
private final String associatedEntityName;
protected final String uniqueKeyPropertyName;
protected final boolean isEmbeddedInXML;
private final boolean eager;
private final boolean unwrapProxy;
private final boolean referenceToPrimaryKey;
private transient Class returnedClass;
/**
* Constructs the requested entity type mapping.
*
* @param scope The type scope
* @param entityName The name of the associated entity.
* @param uniqueKeyPropertyName The property-ref name, or null if we
* reference the PK of the associated entity.
* @param eager Is eager fetching enabled.
* @param isEmbeddedInXML Should values of this mapping be embedded in XML modes?
* @param unwrapProxy Is unwrapping of proxies allowed for this association; unwrapping
* says to return the "implementation target" of lazy prooxies; typically only possible
* with lazy="no-proxy".
*
* @deprecated Use {@link #EntityType(org.hibernate.type.TypeFactory.TypeScope, String, boolean, String, boolean, boolean)} instead.
* See Jira issue: <a href="https://hibernate.onjira.com/browse/HHH-7771">HHH-7771</a>
*/
@Deprecated
protected EntityType(
TypeFactory.TypeScope scope,
String entityName,
String uniqueKeyPropertyName,
boolean eager,
boolean isEmbeddedInXML,
boolean unwrapProxy) {
this( scope, entityName, uniqueKeyPropertyName == null, uniqueKeyPropertyName, eager, unwrapProxy );
}
/**
* Constructs the requested entity type mapping.
*
* @param scope The type scope
* @param entityName The name of the associated entity.
* @param uniqueKeyPropertyName The property-ref name, or null if we
* reference the PK of the associated entity.
* @param eager Is eager fetching enabled.
* @param unwrapProxy Is unwrapping of proxies allowed for this association; unwrapping
* says to return the "implementation target" of lazy prooxies; typically only possible
* with lazy="no-proxy".
*
* @deprecated Use {@link #EntityType(org.hibernate.type.TypeFactory.TypeScope, String, boolean, String, boolean, boolean)} instead.
*/
@Deprecated
protected EntityType(
TypeFactory.TypeScope scope,
String entityName,
String uniqueKeyPropertyName,
boolean eager,
boolean unwrapProxy) {
this( scope, entityName, uniqueKeyPropertyName == null, uniqueKeyPropertyName, eager, unwrapProxy );
}
/**
* Constructs the requested entity type mapping.
*
* @param scope The type scope
* @param entityName The name of the associated entity.
* @param referenceToPrimaryKey True if association references a primary key.
* @param uniqueKeyPropertyName The property-ref name, or null if we
* reference the PK of the associated entity.
* @param eager Is eager fetching enabled.
* @param unwrapProxy Is unwrapping of proxies allowed for this association; unwrapping
* says to return the "implementation target" of lazy prooxies; typically only possible
* with lazy="no-proxy".
*/
protected EntityType(
TypeFactory.TypeScope scope,
String entityName,
boolean referenceToPrimaryKey,
String uniqueKeyPropertyName,
boolean eager,
boolean unwrapProxy) {
this.scope = scope;
this.associatedEntityName = entityName;
this.uniqueKeyPropertyName = uniqueKeyPropertyName;
this.isEmbeddedInXML = true;
this.eager = eager;
this.unwrapProxy = unwrapProxy;
this.referenceToPrimaryKey = referenceToPrimaryKey;
}
protected TypeFactory.TypeScope scope() {
return scope;
}
/**
* An entity type is a type of association type
*
* @return True.
*/
public boolean isAssociationType() {
return true;
}
/**
* Explicitly, an entity type is an entity type ;)
*
* @return True.
*/
public final boolean isEntityType() {
return true;
}
/**
* {@inheritDoc}
*/
public boolean isMutable() {
return false;
}
/**
* Generates a string representation of this type.
*
* @return string rep
*/
public String toString() {
return getClass().getName() + '(' + getAssociatedEntityName() + ')';
}
/**
* For entity types, the name correlates to the associated entity name.
*/
public String getName() {
return associatedEntityName;
}
/**
* Does this association foreign key reference the primary key of the other table?
* Otherwise, it references a property-ref.
*
* @return True if this association reference the PK of the associated entity.
*/
public boolean isReferenceToPrimaryKey() {
return referenceToPrimaryKey;
}
public String getRHSUniqueKeyPropertyName() {
// Return null if this type references a PK. This is important for
// associations' use of mappedBy referring to a derived ID.
return referenceToPrimaryKey ? null : uniqueKeyPropertyName;
}
public String getLHSPropertyName() {
return null;
}
public String getPropertyName() {
return null;
}
/**
* The name of the associated entity.
*
* @return The associated entity name.
*/
public final String getAssociatedEntityName() {
return associatedEntityName;
}
/**
* The name of the associated entity.
*
* @param factory The session factory, for resolution.
* @return The associated entity name.
*/
public String getAssociatedEntityName(SessionFactoryImplementor factory) {
return getAssociatedEntityName();
}
/**
* Retrieves the {@link Joinable} defining the associated entity.
*
* @param factory The session factory.
* @return The associated joinable
* @throws MappingException Generally indicates an invalid entity name.
*/
public Joinable getAssociatedJoinable(SessionFactoryImplementor factory) throws MappingException {
return ( Joinable ) factory.getEntityPersister( associatedEntityName );
}
/**
* This returns the wrong class for an entity with a proxy, or for a named
* entity. Theoretically it should return the proxy class, but it doesn't.
* <p/>
* The problem here is that we do not necessarily have a ref to the associated
* entity persister (nor to the session factory, to look it up) which is really
* needed to "do the right thing" here...
*
* @return The entiyt class.
*/
public final Class getReturnedClass() {
if ( returnedClass == null ) {
returnedClass = determineAssociatedEntityClass();
}
return returnedClass;
}
private Class determineAssociatedEntityClass() {
try {
return ReflectHelper.classForName( getAssociatedEntityName() );
}
catch ( ClassNotFoundException cnfe ) {
return java.util.Map.class;
}
}
/**
* {@inheritDoc}
*/
public Object nullSafeGet(ResultSet rs, String name, SessionImplementor session, Object owner)
throws HibernateException, SQLException {
return nullSafeGet( rs, new String[] {name}, session, owner );
}
/**
* {@inheritDoc}
*/
public final Object nullSafeGet(
ResultSet rs,
String[] names,
SessionImplementor session,
Object owner) throws HibernateException, SQLException {
return resolve( hydrate(rs, names, session, owner), session, owner );
}
/**
* Two entities are considered the same when their instances are the same.
*
*
* @param x One entity instance
* @param y Another entity instance
* @return True if x == y; false otherwise.
*/
public final boolean isSame(Object x, Object y) {
return x == y;
}
/**
* {@inheritDoc}
*/
public int compare(Object x, Object y) {
return 0; //TODO: entities CAN be compared, by PK, fix this! -> only if/when we can extract the id values....
}
/**
* {@inheritDoc}
*/
public Object deepCopy(Object value, SessionFactoryImplementor factory) {
return value; //special case ... this is the leaf of the containment graph, even though not immutable
}
/**
* {@inheritDoc}
*/
public Object replace(
Object original,
Object target,
SessionImplementor session,
Object owner,
Map copyCache) throws HibernateException {
if ( original == null ) {
return null;
}
Object cached = copyCache.get(original);
if ( cached != null ) {
return cached;
}
else {
if ( original == target ) {
return target;
}
if ( session.getContextEntityIdentifier( original ) == null &&
ForeignKeys.isTransient( associatedEntityName, original, Boolean.FALSE, session ) ) {
final Object copy = session.getFactory().getEntityPersister( associatedEntityName )
.instantiate( null, session );
//TODO: should this be Session.instantiate(Persister, ...)?
copyCache.put( original, copy );
return copy;
}
else {
Object id = getIdentifier( original, session );
if ( id == null ) {
throw new AssertionFailure("non-transient entity has a null id");
}
id = getIdentifierOrUniqueKeyType( session.getFactory() )
.replace(id, null, session, owner, copyCache);
return resolve( id, session, owner );
}
}
}
/**
* {@inheritDoc}
*/
public int getHashCode(Object x, SessionFactoryImplementor factory) {
EntityPersister persister = factory.getEntityPersister(associatedEntityName);
if ( !persister.canExtractIdOutOfEntity() ) {
return super.getHashCode( x );
}
final Serializable id;
if (x instanceof HibernateProxy) {
id = ( (HibernateProxy) x ).getHibernateLazyInitializer().getIdentifier();
}
else {
final Class mappedClass = persister.getMappedClass();
if ( mappedClass.isAssignableFrom( x.getClass() ) ) {
id = persister.getIdentifier( x );
}
else {
id = (Serializable) x;
}
}
return persister.getIdentifierType().getHashCode( id, factory );
}
@Override
public boolean isEqual(Object x, Object y, SessionFactoryImplementor factory) {
// associations (many-to-one and one-to-one) can be null...
if ( x == null || y == null ) {
return x == y;
}
EntityPersister persister = factory.getEntityPersister(associatedEntityName);
if ( !persister.canExtractIdOutOfEntity() ) {
return super.isEqual(x, y );
}
final Class mappedClass = persister.getMappedClass();
Serializable xid;
if (x instanceof HibernateProxy) {
xid = ( (HibernateProxy) x ).getHibernateLazyInitializer()
.getIdentifier();
}
else {
if ( mappedClass.isAssignableFrom( x.getClass() ) ) {
xid = persister.getIdentifier( x );
}
else {
//JPA 2 case where @IdClass contains the id and not the associated entity
xid = (Serializable) x;
}
}
Serializable yid;
if (y instanceof HibernateProxy) {
yid = ( (HibernateProxy) y ).getHibernateLazyInitializer()
.getIdentifier();
}
else {
if ( mappedClass.isAssignableFrom( y.getClass() ) ) {
yid = persister.getIdentifier( y );
}
else {
//JPA 2 case where @IdClass contains the id and not the associated entity
yid = (Serializable) y;
}
}
return persister.getIdentifierType()
.isEqual(xid, yid, factory);
}
/**
* {@inheritDoc}
*/
public boolean isEmbeddedInXML() {
return isEmbeddedInXML;
}
/**
* {@inheritDoc}
*/
public boolean isXMLElement() {
return isEmbeddedInXML;
}
/**
* {@inheritDoc}
*/
public Object fromXMLNode(Node xml, Mapping factory) throws HibernateException {
if ( !isEmbeddedInXML ) {
return getIdentifierType(factory).fromXMLNode(xml, factory);
}
else {
return xml;
}
}
/**
* {@inheritDoc}
*/
public void setToXMLNode(Node node, Object value, SessionFactoryImplementor factory) throws HibernateException {
if ( !isEmbeddedInXML ) {
getIdentifierType(factory).setToXMLNode(node, value, factory);
}
else {
Element elt = (Element) value;
replaceNode( node, new ElementWrapper(elt) );
}
}
public String getOnCondition(String alias, SessionFactoryImplementor factory, Map enabledFilters)
throws MappingException {
if ( isReferenceToPrimaryKey() ) { //TODO: this is a bit arbitrary, expose a switch to the user?
return "";
}
else {
return getAssociatedJoinable( factory ).filterFragment( alias, enabledFilters );
}
}
/**
* Resolve an identifier or unique key value
*/
public Object resolve(Object value, SessionImplementor session, Object owner) throws HibernateException {
if ( isNotEmbedded( session ) ) {
return value;
}
if ( value != null && !isNull( owner, session ) ) {
if ( isReferenceToPrimaryKey() ) {
return resolveIdentifier( (Serializable) value, session );
}
else if ( uniqueKeyPropertyName != null ) {
return loadByUniqueKey( getAssociatedEntityName(), uniqueKeyPropertyName, value, session );
}
}
return null;
}
public Type getSemiResolvedType(SessionFactoryImplementor factory) {
return factory.getEntityPersister( associatedEntityName ).getIdentifierType();
}
protected final Object getIdentifier(Object value, SessionImplementor session) throws HibernateException {
if ( isNotEmbedded(session) ) {
return value;
}
if ( isReferenceToPrimaryKey() || uniqueKeyPropertyName == null ) {
return ForeignKeys.getEntityIdentifierIfNotUnsaved( getAssociatedEntityName(), value, session ); //tolerates nulls
}
else if ( value == null ) {
return null;
}
else {
EntityPersister entityPersister = session.getFactory().getEntityPersister( getAssociatedEntityName() );
Object propertyValue = entityPersister.getPropertyValue( value, uniqueKeyPropertyName );
// We now have the value of the property-ref we reference. However,
// we need to dig a little deeper, as that property might also be
// an entity type, in which case we need to resolve its identitifier
Type type = entityPersister.getPropertyType( uniqueKeyPropertyName );
if ( type.isEntityType() ) {
propertyValue = ( ( EntityType ) type ).getIdentifier( propertyValue, session );
}
return propertyValue;
}
}
/**
* @deprecated To be removed in 5. Removed as part of removing the notion of DOM entity-mode.
* See Jira issue: <a href="https://hibernate.onjira.com/browse/HHH-7771">HHH-7771</a>
*/
@Deprecated
protected boolean isNotEmbedded(SessionImplementor session) {
// return !isEmbeddedInXML;
return false;
}
/**
* Generate a loggable representation of an instance of the value mapped by this type.
*
* @param value The instance to be logged.
* @param factory The session factory.
* @return The loggable string.
* @throws HibernateException Generally some form of resolution problem.
*/
public String toLoggableString(Object value, SessionFactoryImplementor factory) {
if ( value == null ) {
return "null";
}
EntityPersister persister = factory.getEntityPersister( associatedEntityName );
StringBuilder result = new StringBuilder().append( associatedEntityName );
if ( persister.hasIdentifierProperty() ) {
final EntityMode entityMode = persister.getEntityMode();
final Serializable id;
if ( entityMode == null ) {
if ( isEmbeddedInXML ) {
throw new ClassCastException( value.getClass().getName() );
}
id = ( Serializable ) value;
} else if ( value instanceof HibernateProxy ) {
HibernateProxy proxy = ( HibernateProxy ) value;
id = proxy.getHibernateLazyInitializer().getIdentifier();
}
else {
id = persister.getIdentifier( value );
}
result.append( '#' )
.append( persister.getIdentifierType().toLoggableString( id, factory ) );
}
return result.toString();
}
/**
* Is the association modeled here defined as a 1-1 in the database (physical model)?
*
* @return True if a 1-1 in the database; false otherwise.
*/
public abstract boolean isOneToOne();
/**
* Is the association modeled here a 1-1 according to the logical moidel?
*
* @return True if a 1-1 in the logical model; false otherwise.
*/
public boolean isLogicalOneToOne() {
return isOneToOne();
}
/**
* Convenience method to locate the identifier type of the associated entity.
*
* @param factory The mappings...
* @return The identifier type
*/
Type getIdentifierType(Mapping factory) {
return factory.getIdentifierType( getAssociatedEntityName() );
}
/**
* Convenience method to locate the identifier type of the associated entity.
*
* @param session The originating session
* @return The identifier type
*/
Type getIdentifierType(SessionImplementor session) {
return getIdentifierType( session.getFactory() );
}
/**
* Determine the type of either (1) the identifier if we reference the
* associated entity's PK or (2) the unique key to which we refer (i.e.
* the property-ref).
*
* @param factory The mappings...
* @return The appropriate type.
* @throws MappingException Generally, if unable to resolve the associated entity name
* or unique key property name.
*/
public final Type getIdentifierOrUniqueKeyType(Mapping factory) throws MappingException {
if ( isReferenceToPrimaryKey() || uniqueKeyPropertyName == null ) {
return getIdentifierType(factory);
}
else {
Type type = factory.getReferencedPropertyType( getAssociatedEntityName(), uniqueKeyPropertyName );
if ( type.isEntityType() ) {
type = ( ( EntityType ) type).getIdentifierOrUniqueKeyType( factory );
}
return type;
}
}
/**
* The name of the property on the associated entity to which our FK
* refers
*
* @param factory The mappings...
* @return The appropriate property name.
* @throws MappingException Generally, if unable to resolve the associated entity name
*/
public final String getIdentifierOrUniqueKeyPropertyName(Mapping factory)
throws MappingException {
if ( isReferenceToPrimaryKey() || uniqueKeyPropertyName == null ) {
return factory.getIdentifierPropertyName( getAssociatedEntityName() );
}
else {
return uniqueKeyPropertyName;
}
}
protected abstract boolean isNullable();
/**
* Resolve an identifier via a load.
*
* @param id The entity id to resolve
* @param session The orginating session.
* @return The resolved identifier (i.e., loaded entity).
* @throws org.hibernate.HibernateException Indicates problems performing the load.
*/
protected final Object resolveIdentifier(Serializable id, SessionImplementor session) throws HibernateException {
boolean isProxyUnwrapEnabled = unwrapProxy &&
session.getFactory()
.getEntityPersister( getAssociatedEntityName() )
.isInstrumented();
Object proxyOrEntity = session.internalLoad(
getAssociatedEntityName(),
id,
eager,
isNullable() && !isProxyUnwrapEnabled
);
if ( proxyOrEntity instanceof HibernateProxy ) {
( ( HibernateProxy ) proxyOrEntity ).getHibernateLazyInitializer()
.setUnwrap( isProxyUnwrapEnabled );
}
return proxyOrEntity;
}
protected boolean isNull(Object owner, SessionImplementor session) {
return false;
}
/**
* Load an instance by a unique key that is not the primary key.
*
* @param entityName The name of the entity to load
* @param uniqueKeyPropertyName The name of the property defining the uniqie key.
* @param key The unique key property value.
* @param session The originating session.
* @return The loaded entity
* @throws HibernateException generally indicates problems performing the load.
*/
public Object loadByUniqueKey(
String entityName,
String uniqueKeyPropertyName,
Object key,
SessionImplementor session) throws HibernateException {
final SessionFactoryImplementor factory = session.getFactory();
UniqueKeyLoadable persister = ( UniqueKeyLoadable ) factory.getEntityPersister( entityName );
//TODO: implement caching?! proxies?!
EntityUniqueKey euk = new EntityUniqueKey(
entityName,
uniqueKeyPropertyName,
key,
getIdentifierOrUniqueKeyType( factory ),
persister.getEntityMode(),
session.getFactory()
);
final PersistenceContext persistenceContext = session.getPersistenceContext();
Object result = persistenceContext.getEntity( euk );
if ( result == null ) {
result = persister.loadByUniqueKey( uniqueKeyPropertyName, key, session );
}
return result == null ? null : persistenceContext.proxyFor( result );
}
}