forked from nhibernate/nhibernate-core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPocoEntityTuplizer.cs
393 lines (341 loc) · 11.6 KB
/
PocoEntityTuplizer.cs
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
using System;
using System.Collections.Generic;
using System.Reflection;
using NHibernate.Bytecode;
using NHibernate.Classic;
using NHibernate.Engine;
using NHibernate.Mapping;
using NHibernate.Properties;
using NHibernate.Proxy;
using NHibernate.Type;
using NHibernate.Util;
using System.Runtime.Serialization;
using NHibernate.Bytecode.Lightweight;
using NHibernate.Intercept;
namespace NHibernate.Tuple.Entity
{
/// <summary> An <see cref="IEntityTuplizer"/> specific to the POCO entity mode. </summary>
public class PocoEntityTuplizer : AbstractEntityTuplizer
{
private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(PocoEntityTuplizer));
private readonly System.Type mappedClass;
private readonly System.Type proxyInterface;
private readonly bool islifecycleImplementor;
private readonly bool isValidatableImplementor;
[NonSerialized]
private IReflectionOptimizer optimizer;
private readonly IProxyValidator proxyValidator;
private readonly IBytecodeEnhancementMetadata _enhancementMetadata;
[NonSerialized]
private bool isBytecodeProviderImpl; // 6.0 TODO: remove
[OnDeserialized]
internal void OnDeserialized(StreamingContext context)
{
SetReflectionOptimizer();
if (optimizer != null)
{
// Also set the InstantiationOptimizer on the deserialized PocoInstantiator.
((PocoInstantiator)Instantiator).SetOptimizer(optimizer.InstantiationOptimizer);
}
ClearOptimizerWhenUsingCustomAccessors();
}
protected void SetReflectionOptimizer()
{
if (Cfg.Environment.UseReflectionOptimizer)
{
// NH different behavior fo NH-1587
optimizer = Cfg.Environment.BytecodeProvider.GetReflectionOptimizer(mappedClass, getters, setters, idGetter, idSetter);
isBytecodeProviderImpl = Cfg.Environment.BytecodeProvider is BytecodeProviderImpl;
}
}
public PocoEntityTuplizer(EntityMetamodel entityMetamodel, PersistentClass mappedEntity)
: base(entityMetamodel, mappedEntity)
{
mappedClass = mappedEntity.MappedClass;
proxyInterface = mappedEntity.ProxyInterface;
islifecycleImplementor = typeof(ILifecycle).IsAssignableFrom(mappedClass);
isValidatableImplementor = typeof(IValidatable).IsAssignableFrom(mappedClass);
_enhancementMetadata = EntityMetamodel.BytecodeEnhancementMetadata;
SetReflectionOptimizer();
Instantiator = BuildInstantiator(mappedEntity);
ClearOptimizerWhenUsingCustomAccessors();
proxyValidator = Cfg.Environment.BytecodeProvider.ProxyFactoryFactory.ProxyValidator;
}
public override System.Type ConcreteProxyClass
{
get { return proxyInterface; }
}
public override bool IsInstrumented => _enhancementMetadata.EnhancedForLazyLoading;
public override System.Type MappedClass
{
get { return mappedClass; }
}
protected override IGetter BuildPropertyGetter(Mapping.Property mappedProperty, PersistentClass mappedEntity)
{
return mappedProperty.GetGetter(mappedEntity.MappedClass);
}
protected override ISetter BuildPropertySetter(Mapping.Property mappedProperty, PersistentClass mappedEntity)
{
return mappedProperty.GetSetter(mappedEntity.MappedClass);
}
protected override IInstantiator BuildInstantiator(PersistentClass persistentClass)
{
if (optimizer == null)
{
log.Debug("Create Instantiator without optimizer for:{0}", persistentClass.MappedClass.FullName);
return new PocoEntityInstantiator(EntityMetamodel, persistentClass, null, ProxyFactory);
}
else
{
log.Debug("Create Instantiator using optimizer for:{0}", persistentClass.MappedClass.FullName);
return new PocoEntityInstantiator(EntityMetamodel, persistentClass, optimizer.InstantiationOptimizer, ProxyFactory);
}
}
protected override IProxyFactory BuildProxyFactory(PersistentClass persistentClass, IGetter idGetter, ISetter idSetter)
{
bool isInterface = false;
// determine the id getter and setter methods from the proxy interface (if any)
// determine all interfaces needed by the resulting proxy
var proxyInterfaces = new HashSet<System.Type> {typeof (INHibernateProxy)};
System.Type _mappedClass = persistentClass.MappedClass;
System.Type _proxyInterface = persistentClass.ProxyInterface;
if (_proxyInterface != null && _mappedClass != _proxyInterface)
{
if (!_proxyInterface.IsInterface)
{
throw new MappingException("proxy must be either an interface, or the class itself: " + EntityName);
}
isInterface = true;
proxyInterfaces.Add(_proxyInterface);
}
if (_mappedClass.IsInterface)
{
isInterface = true;
proxyInterfaces.Add(_mappedClass);
}
foreach (Subclass subclass in persistentClass.SubclassIterator)
{
System.Type subclassProxy = subclass.ProxyInterface;
System.Type subclassClass = subclass.MappedClass;
if (subclassProxy != null && subclassClass != subclassProxy)
{
if (!subclassProxy.IsInterface)
{
throw new MappingException("proxy must be either an interface, or the class itself: " + subclass.EntityName);
}
proxyInterfaces.Add(subclassProxy);
}
}
/*
* NH Different Implementation (for Error logging):
* - Check if the logger is enabled
* - Don't need nothing to check if the mapped-class or proxy is an interface
*/
if (!isInterface && log.IsErrorEnabled())
{
LogPropertyAccessorsErrors(persistentClass);
}
/**********************************************************/
MethodInfo idGetterMethod = idGetter == null ? null : idGetter.Method;
MethodInfo idSetterMethod = idSetter == null ? null : idSetter.Method;
MethodInfo proxyGetIdentifierMethod = idGetterMethod == null || _proxyInterface == null ? null :
ReflectHelper.TryGetMethod(_proxyInterface, idGetterMethod);
MethodInfo proxySetIdentifierMethod = idSetterMethod == null || _proxyInterface == null ? null :
ReflectHelper.TryGetMethod(_proxyInterface, idSetterMethod);
IProxyFactory pf = BuildProxyFactoryInternal(persistentClass, idGetter, idSetter);
try
{
pf.PostInstantiate(
EntityName,
_mappedClass,
proxyInterfaces,
proxyGetIdentifierMethod,
proxySetIdentifierMethod,
persistentClass.HasEmbeddedIdentifier
? (IAbstractComponentType) persistentClass.Identifier.Type
: null,
!isInterface);
}
catch (HibernateException he)
{
log.Warn(he, "could not create proxy factory for:{0}", EntityName);
pf = null;
}
return pf;
}
private void LogPropertyAccessorsErrors(PersistentClass persistentClass)
{
if (proxyValidator == null)
{
return;
}
// This method work when Environment.UseProxyValidator is off
System.Type clazz = persistentClass.MappedClass;
foreach (Mapping.Property property in persistentClass.PropertyIterator)
{
MethodInfo method = property.GetGetter(clazz).Method;
if (!proxyValidator.IsProxeable(method))
{
log.Error("Getters of lazy classes cannot be final: {0}.{1}", persistentClass.MappedClass.FullName,
property.Name);
}
method = property.GetSetter(clazz).Method;
if (!proxyValidator.IsProxeable(method))
{
log.Error("Setters of lazy classes cannot be final: {0}.{1}", persistentClass.MappedClass.FullName,
property.Name);
}
}
}
protected virtual IProxyFactory BuildProxyFactoryInternal(PersistentClass @class, IGetter getter, ISetter setter)
{
return Cfg.Environment.BytecodeProvider.ProxyFactoryFactory.BuildProxyFactory();
}
public override void AfterInitialize(object entity, ISessionImplementor session)
{
if (IsInstrumented)
{
var interceptor = _enhancementMetadata.ExtractInterceptor(entity);
if (interceptor == null)
{
interceptor = _enhancementMetadata.InjectInterceptor(entity, session);
}
else
{
interceptor.Session = session;
}
interceptor?.ClearDirty();
}
}
public override object GetPropertyValue(object entity, int i)
{
if (isBytecodeProviderImpl && optimizer?.AccessOptimizer != null)
{
return optimizer.AccessOptimizer.GetPropertyValue(entity, i);
}
return base.GetPropertyValue(entity, i);
}
public override object[] GetPropertyValues(object entity)
{
if (ShouldGetAllProperties(entity) && optimizer != null && optimizer.AccessOptimizer != null)
{
return GetPropertyValuesWithOptimizer(entity);
}
else
{
return base.GetPropertyValues(entity);
}
}
private object[] GetPropertyValuesWithOptimizer(object entity)
{
return optimizer.AccessOptimizer.GetPropertyValues(entity);
}
public override object[] GetPropertyValuesToInsert(object entity, System.Collections.IDictionary mergeMap, ISessionImplementor session)
{
if (ShouldGetAllProperties(entity) && optimizer != null && optimizer.AccessOptimizer != null)
{
return GetPropertyValuesWithOptimizer(entity);
}
else
{
return base.GetPropertyValuesToInsert(entity, mergeMap, session);
}
}
public override bool HasUninitializedLazyProperties(object entity)
{
if (EntityMetamodel.HasLazyProperties)
{
return _enhancementMetadata.HasAnyUninitializedLazyProperties(entity);
}
else
{
return false;
}
}
internal override ISet<string> GetUninitializedLazyProperties(object entity)
{
if (!EntityMetamodel.HasLazyProperties)
{
return CollectionHelper.EmptySet<string>();
}
return _enhancementMetadata.GetUninitializedLazyProperties(entity);
}
public override bool IsLifecycleImplementor
{
get { return islifecycleImplementor; }
}
public override void SetPropertyValue(object entity, int i, object value)
{
// If there is no property setter we need to manually intercept value for proper lazy property handling.
if (IsInstrumented && setters[i].PropertyName == null)
{
IFieldInterceptor interceptor = _enhancementMetadata.ExtractInterceptor(entity);
if (interceptor != null)
{
value = interceptor.Intercept(entity, EntityMetamodel.PropertyNames[i], value, true);
}
}
if (isBytecodeProviderImpl && optimizer?.AccessOptimizer != null)
{
optimizer.AccessOptimizer.SetPropertyValue(entity, i, value);
return;
}
base.SetPropertyValue(entity, i, value);
}
public override void SetPropertyValues(object entity, object[] values)
{
if (!EntityMetamodel.HasLazyProperties && optimizer != null && optimizer.AccessOptimizer != null)
{
SetPropertyValuesWithOptimizer(entity, values);
}
else
{
base.SetPropertyValues(entity, values);
}
}
private void SetPropertyValuesWithOptimizer(object entity, object[] values)
{
try
{
optimizer.AccessOptimizer.SetPropertyValues(entity, values);
}
catch (InvalidCastException e)
{
throw new PropertyAccessException(e, "Invalid Cast (check your mapping for property type mismatches);", true,
entity.GetType());
}
}
public override bool IsValidatableImplementor
{
get { return isValidatableImplementor; }
}
public override EntityMode EntityMode
{
get { return EntityMode.Poco; }
}
protected void ClearOptimizerWhenUsingCustomAccessors()
{
if (hasCustomAccessors)
{
optimizer = null;
}
}
protected override object GetIdentifierPropertyValue(object entity)
{
if (isBytecodeProviderImpl && optimizer?.AccessOptimizer != null)
{
return optimizer.AccessOptimizer.GetSpecializedPropertyValue(entity);
}
return base.GetIdentifierPropertyValue(entity);
}
protected override void SetIdentifierPropertyValue(object entity, object value)
{
if (isBytecodeProviderImpl && optimizer?.AccessOptimizer != null)
{
optimizer.AccessOptimizer.SetSpecializedPropertyValue(entity, value);
return;
}
base.SetIdentifierPropertyValue(entity, value);
}
}
}