/
AbstractContainerMapping.java
419 lines (391 loc) · 14.9 KB
/
AbstractContainerMapping.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
/**********************************************************************
Copyright (c) 2005 Andy Jefferson and others. All rights reserved.
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.
Contributors:
...
**********************************************************************/
package org.datanucleus.store.rdbms.mapping.java;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import org.datanucleus.ClassLoaderResolver;
import org.datanucleus.ClassNameConstants;
import org.datanucleus.ExecutionContext;
import org.datanucleus.api.ApiAdapter;
import org.datanucleus.exceptions.NucleusException;
import org.datanucleus.exceptions.NucleusUserException;
import org.datanucleus.metadata.AbstractMemberMetaData;
import org.datanucleus.metadata.MetaDataUtils;
import org.datanucleus.state.ObjectProvider;
import org.datanucleus.store.rdbms.exceptions.NoDatastoreMappingException;
import org.datanucleus.store.rdbms.mapping.datastore.DatastoreMapping;
import org.datanucleus.store.rdbms.table.Table;
import org.datanucleus.store.types.SCO;
import org.datanucleus.store.types.SCOUtils;
/**
* Mapping for a field that represents a container of objects, such as a List,
* a Set, a Collection, a Map, or an array. Has an owner table.
* Can be represented in the following ways :-
* <ul>
* <li>Using a Join-Table, where the linkage between owner and elements/keys/values is stored in this table</li>
* <li>Using a Foreign-Key in the element/key/value</li>
* <li>Serialised into a single column in the owner table.</li>
* <li>Embedded into the Join-Table</li>
* <li>Serialised into a single-column in the Join-Table</li>
* </ul>
* The contents of the container are backed by a store, handling interfacing with the datastore.
*/
public abstract class AbstractContainerMapping extends SingleFieldMapping
{
/**
* Initialize this JavaTypeMapping for the given field/property.
* @param mmd MetaData for the field/property to be mapped (if any)
* @param table The datastore container storing this mapping (if any)
* @param clr the ClassLoaderResolver
*/
public void initialize(AbstractMemberMetaData mmd, Table table, ClassLoaderResolver clr)
{
super.initialize(mmd, table, clr);
if (mmd.getContainer() == null)
{
throw new NucleusUserException(LOCALISER_RDBMS.msg("041023", mmd.getFullFieldName()));
}
if (!containerIsStoredInSingleColumn())
{
// Not serialised so we use JoinTable or ForeignKey
storeMgr.newJoinDatastoreContainerObject(mmd, clr);
}
}
/**
* Whether the mapping has a simple (single column) datastore representation.
* @return Whether it has a simple datastore representation (single column)
*/
public boolean hasSimpleDatastoreRepresentation()
{
return false;
}
/**
* Method to prepare a field mapping for use in the datastore.
* This creates the column in the table.
*/
protected void prepareDatastoreMapping()
{
if (containerIsStoredInSingleColumn())
{
// Serialised collections/maps/arrays should just create a (typically BLOB) column as normal in the owning table
super.prepareDatastoreMapping();
}
}
/**
* Accessor for the name of the java-type actually used when mapping the particular datastore
* field. This java-type must have an entry in the datastore mappings.
* @param index requested datastore field index.
* @return the name of java-type for the requested datastore field.
*/
public String getJavaTypeForDatastoreMapping(int index)
{
if (containerIsStoredInSingleColumn())
{
// Serialised container so just return serialised
return ClassNameConstants.JAVA_IO_SERIALIZABLE;
}
return super.getJavaTypeForDatastoreMapping(index);
}
/**
* Method to set a field in the passed JDBC PreparedStatement using this mapping.
* Only valid when the collection is serialised.
* @param ec ExecutionContext
* @param ps The JDBC Prepared Statement to be populated
* @param exprIndex The parameter positions in the JDBC statement to populate.
* @param value The value to populate into it
*/
public void setObject(ExecutionContext ec, PreparedStatement ps, int[] exprIndex, Object value)
{
if (mmd == null || !containerIsStoredInSingleColumn())
{
throw new NucleusException(failureMessage("setObject")).setFatal();
}
ObjectProvider[] sms = null;
ApiAdapter api = ec.getApiAdapter();
if (value != null)
{
Collection smsColl = null;
if (value instanceof java.util.Collection)
{
Iterator elementsIter = ((java.util.Collection)value).iterator();
while (elementsIter.hasNext())
{
Object elem = elementsIter.next();
if (api.isPersistable(elem))
{
ObjectProvider sm = ec.findObjectProvider(elem);
if (sm != null)
{
if (smsColl == null)
{
smsColl = new HashSet();
}
smsColl.add(sm);
}
}
}
}
else if (value instanceof java.util.Map)
{
Iterator entriesIter = ((java.util.Map)value).entrySet().iterator();
while (entriesIter.hasNext())
{
Map.Entry entry = (Map.Entry)entriesIter.next();
Object key = entry.getKey();
Object val = entry.getValue();
if (api.isPersistable(key))
{
ObjectProvider sm = ec.findObjectProvider(key);
if (sm != null)
{
if (smsColl == null)
{
smsColl = new HashSet();
}
smsColl.add(sm);
}
}
if (api.isPersistable(val))
{
ObjectProvider sm = ec.findObjectProvider(val);
if (sm != null)
{
if (smsColl == null)
{
smsColl = new HashSet();
}
smsColl.add(sm);
}
}
}
}
if (smsColl != null)
{
sms = (ObjectProvider[])smsColl.toArray(new ObjectProvider[smsColl.size()]);
}
}
if (sms != null)
{
// Set all PC objects as being stored (so we dont detach them in any serialisation process)
for (int i=0;i<sms.length;i++)
{
sms[i].setStoringPC();
}
}
getDatastoreMapping(0).setObject(ps, exprIndex[0], value);
if (sms != null)
{
// Unset all PC objects now they are stored
for (int i=0;i<sms.length;i++)
{
sms[i].unsetStoringPC();
}
}
}
/**
* Method to retrieve an object from the passed JDBC ResultSet.
* Only valid when the collection is serialised.
* @param ec ExecutionContext
* @param resultSet The ResultSet
* @param exprIndex The parameter position(s) to extract the object from
* @return The collection object
*/
public Object getObject(ExecutionContext ec, ResultSet resultSet, int[] exprIndex)
{
if (mmd == null || !containerIsStoredInSingleColumn())
{
throw new NucleusException(failureMessage("getObject")).setFatal();
}
return getDatastoreMapping(0).getObject(resultSet, exprIndex[0]);
}
/**
* Accessor for the datastore class.
* @return The datastore class
*/
public Table getTable()
{
if (containerIsStoredInSingleColumn())
{
// Serialised into owner table
return table;
}
else
{
return null;
}
}
/**
* Accessor for the number of datastore fields
* @return The number of datastore fields
*/
public int getNumberOfDatastoreMappings()
{
if (containerIsStoredInSingleColumn())
{
// Serialised into owner table
return super.getNumberOfDatastoreMappings();
}
else
{
// By default, we have no columns as such for the container
return 0;
}
}
/**
* Accessor for a datastore mapping
* @param index The id of the mapping
* @return The datastore mapping
*/
public DatastoreMapping getDatastoreMapping(int index)
{
if (containerIsStoredInSingleColumn())
{
// Serialised into owner table
return super.getDatastoreMapping(index);
}
else
{
throw new NoDatastoreMappingException(mmd.getName());
}
}
/**
* Accessor for the datastore mappings for this java type
* @return The datastore mapping(s)
*/
public DatastoreMapping[] getDatastoreMappings()
{
if (containerIsStoredInSingleColumn())
{
// Serialised into owner table
return super.getDatastoreMappings();
}
else
{
throw new NoDatastoreMappingException(mmd.getName());
}
}
/**
* Convenience method to return if the container (collection or map) is stored
* in the owning table as a column. The container is stored in a single column in the following situations :-
* <UL>
* <LI>The FieldMetaData has 'serialized="true"'</LI>
* <LI>The collection has embedded-element="true" but no join table (and so serialised)</LI>
* <LI>The map has embedded-key/value="true" but no join table (and so serialised)</LI>
* <LI>The array has embedded-element="true" but no join table (and so serialised)</LI>
* <LI>The array has no join table and non-PC elements (and so serialised)</LI>
* </UL>
* @return Whether it is stored in a single column in the main table.
*/
protected boolean containerIsStoredInSingleColumn()
{
if (mmd != null && mmd.isSerialized())
{
return true;
}
else if (mmd != null && mmd.hasCollection() && SCOUtils.collectionHasSerialisedElements(mmd))
{
return true; // No join specified but serialised elements so serialise the field
}
else if (mmd != null && mmd.hasMap() && SCOUtils.mapHasSerialisedKeysAndValues(mmd))
{
return true; // No join specified but serialised keys/values so serialise the field
}
else if (mmd != null && mmd.hasArray() &&
SCOUtils.arrayIsStoredInSingleColumn(mmd, storeMgr.getMetaDataManager()))
{
if (MetaDataUtils.getInstance().arrayStorableAsByteArrayInSingleColumn(mmd))
{
return false; // Storable as byte array
}
else
{
return true; // No join specified but serialised elements so serialise the field
}
}
else
{
return false;
}
}
/**
* This mapping is included in the select statement.
* @return Whether to include in select statement
*/
public boolean includeInFetchStatement()
{
// Only include in a fetch when it is serialised into 1 column
return containerIsStoredInSingleColumn();
}
/**
* This mapping is included in the update statement.
* @return Whether to include in update statement
*/
public boolean includeInUpdateStatement()
{
// Only include in an update when it is serialised into 1 column
return containerIsStoredInSingleColumn();
}
/**
* This mapping is included in the insert statement.
* @return Whether to include in insert statement
*/
public boolean includeInInsertStatement()
{
// Only include in an insert when it is serialised into 1 column
return containerIsStoredInSingleColumn();
}
/**
* Method to replace the field that this mapping represents with a SCO wrapper.
* The wrapper will be suitable for the passed instantiated type and if it is null will be for
* the declared type of the field.
* @param op ObjectProvider for the owning object
* @param value The value to create the wrapper with
* @param forInsert Whether to insert the SCO with this value
* @param forUpdate Whether to update the SCO with this value
* @return The SCO wrapper object that the field was replaced with
*/
protected SCO replaceFieldWithWrapper(ObjectProvider op, Object value, boolean forInsert, boolean forUpdate)
{
Class type = mmd.getType();
if( value!= null)
{
type = value.getClass();
}
else if (mmd.getOrderMetaData()!=null && type.isAssignableFrom(java.util.List.class))
{
type = java.util.List.class;
}
SCO sco = SCOUtils.newSCOInstance(op, mmd, mmd.getType(), type, value, forInsert, forUpdate, true);
return sco;
}
// ---------------- Implementation of MappingCallbacks --------------------
/**
* Method to be called after any fetch of the owner class element.
* @param sm StateManager of the owner
*/
public void postFetch(ObjectProvider sm)
{
if (containerIsStoredInSingleColumn())
{
// Do nothing when serialised since we are handled in the main request
return;
}
replaceFieldWithWrapper(sm, null, false, false);
}
}