Elffuss BraidHub

kikocis/java-driver public

0c8d75acc5a0 · 40.4 KiBRawPermalink
1/*
2 * Copyright (C) 2012-2015 DataStax Inc.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16package com.datastax.driver.mapping;
17
18import com.datastax.driver.core.*;
19import com.datastax.driver.core.querybuilder.Delete;
20import com.datastax.driver.core.querybuilder.Insert;
21import com.datastax.driver.core.querybuilder.QueryBuilder;
22import com.datastax.driver.mapping.Mapper.Option.SaveNullFields;
23import com.datastax.driver.mapping.annotations.Accessor;
24import com.datastax.driver.mapping.annotations.Computed;
25import com.google.common.base.Function;
26import com.google.common.base.Functions;
27import com.google.common.base.Objects;
28import com.google.common.base.Preconditions;
29import com.google.common.util.concurrent.Futures;
30import com.google.common.util.concurrent.ListenableFuture;
31import org.slf4j.Logger;
32import org.slf4j.LoggerFactory;
33
34import java.util.*;
35
36import static com.datastax.driver.mapping.Mapper.Option.Type.SAVE_NULL_FIELDS;
37import static com.google.common.base.Preconditions.checkArgument;
38
39/**
40 * An object handling the mapping of a particular class.
41 * <p/>
42 * A {@code Mapper} object is obtained from a {@code MappingManager} using the
43 * {@link MappingManager#mapper} method.
44 */
45public class Mapper<T> {
46
47 private static final Logger logger = LoggerFactory.getLogger(EntityMapper.class);
48
49 final MappingManager manager;
50 final ProtocolVersion protocolVersion;
51 final Class<T> klass;
52 final EntityMapper<T> mapper;
53 final TableMetadata tableMetadata;
54
55 // Cache prepared statements for each type of query we use.
56 private volatile Map<MapperQueryKey, PreparedStatement> preparedQueries = Collections.emptyMap();
57
58 private static final Function<Object, Void> NOOP = Functions.constant(null);
59
60 private volatile EnumMap<Option.Type, Option> defaultSaveOptions;
61 private volatile EnumMap<Option.Type, Option> defaultGetOptions;
62 private volatile EnumMap<Option.Type, Option> defaultDeleteOptions;
63
64 private static final EnumMap<Option.Type, Option> NO_OPTIONS = new EnumMap<Option.Type, Option>(Option.Type.class);
65
66 final Function<ResultSet, T> mapOneFunction;
67 final Function<ResultSet, T> mapOneFunctionWithoutAliases;
68 final Function<ResultSet, Result<T>> mapAllFunctionWithoutAliases;
69
70 Mapper(MappingManager manager, Class<T> klass, EntityMapper<T> mapper) {
71 this.manager = manager;
72 this.klass = klass;
73 this.mapper = mapper;
74
75 KeyspaceMetadata keyspace = session().getCluster().getMetadata().getKeyspace(mapper.getKeyspace());
76 this.tableMetadata = keyspace == null ? null : keyspace.getTable(mapper.getTable());
77
78 this.protocolVersion = manager.getSession().getCluster().getConfiguration().getProtocolOptions().getProtocolVersionEnum();
79 this.mapOneFunction = new Function<ResultSet, T>() {
80 public T apply(ResultSet rs) {
81 return Mapper.this.mapAliased(rs).one();
82 }
83 };
84 this.mapOneFunctionWithoutAliases = new Function<ResultSet, T>() {
85 public T apply(ResultSet rs) {
86 return Mapper.this.map(rs).one();
87 }
88 };
89 this.mapAllFunctionWithoutAliases = new Function<ResultSet, Result<T>>() {
90 public Result<T> apply(ResultSet rs) {
91 return Mapper.this.map(rs);
92 }
93 };
94
95 this.defaultSaveOptions = NO_OPTIONS;
96 this.defaultGetOptions = NO_OPTIONS;
97 this.defaultDeleteOptions = NO_OPTIONS;
98 }
99
100 Session session() {
101 return manager.getSession();
102 }
103
104 PreparedStatement getPreparedQuery(QueryType type, Set<ColumnMapper<?>> columns, EnumMap<Option.Type, Option> options) {
105
106 MapperQueryKey pqk = new MapperQueryKey(type, columns, options);
107
108 PreparedStatement stmt = preparedQueries.get(pqk);
109 if (stmt == null) {
110 synchronized (preparedQueries) {
111 stmt = preparedQueries.get(pqk);
112 if (stmt == null) {
113 String queryString = type.makePreparedQueryString(tableMetadata, mapper, manager, columns, options.values());
114 logger.debug("Preparing query {}", queryString);
115 stmt = session().prepare(queryString);
116 Map<MapperQueryKey, PreparedStatement> newQueries = new HashMap<MapperQueryKey, PreparedStatement>(preparedQueries);
117 newQueries.put(pqk, stmt);
118 preparedQueries = newQueries;
119 }
120 }
121 }
122 return stmt;
123 }
124
125 PreparedStatement getPreparedQuery(QueryType type, EnumMap<Option.Type, Option> options) {
126 return getPreparedQuery(type, Collections.<ColumnMapper<?>>emptySet(), options);
127 }
128
129 /**
130 * The {@code TableMetadata} for this mapper.
131 *
132 * @return the {@code TableMetadata} for this mapper or {@code null} if keyspace is not set.
133 */
134 public TableMetadata getTableMetadata() {
135 return tableMetadata;
136 }
137
138 /**
139 * The {@code MappingManager} managing this mapper.
140 *
141 * @return the {@code MappingManager} managing this mapper.
142 */
143 public MappingManager getManager() {
144 return manager;
145 }
146
147 /**
148 * Creates a query that can be used to save the provided entity.
149 * <p/>
150 * This method is useful if you want to setup a number of options (tracing,
151 * conistency level, ...) of the returned statement before executing it manually
152 * or need access to the {@code ResultSet} object after execution (to get the
153 * trace, the execution info, ...), but in other cases, calling {@link #save}
154 * or {@link #saveAsync} is shorter.
155 *
156 * @param entity the entity to save.
157 * @return a query that saves {@code entity} (based on it's defined mapping).
158 */
159 public Statement saveQuery(T entity) {
160 return saveQuery(entity, this.defaultSaveOptions);
161 }
162
163 /**
164 * Creates a query that can be used to save the provided entity.
165 * <p/>
166 * This method is useful if you want to setup a number of options (tracing,
167 * conistency level, ...) of the returned statement before executing it manually
168 * or need access to the {@code ResultSet} object after execution (to get the
169 * trace, the execution info, ...), but in other cases, calling {@link #save}
170 * or {@link #saveAsync} is shorter.
171 * This method allows you to provide a suite of {@link Option} to include in
172 * the SAVE query. Options currently supported for SAVE are :
173 * <ul>
174 * <li>Timestamp</li>
175 * <li>Time-to-live (ttl)</li>
176 * <li>Consistency level</li>
177 * <li>Tracing</li>
178 * </ul>
179 *
180 * @param entity the entity to save.
181 * @return a query that saves {@code entity} (based on it's defined mapping).
182 */
183 public Statement saveQuery(T entity, Option... options) {
184 return saveQuery(entity, toMapWithDefaults(options, this.defaultSaveOptions));
185 }
186
187 private Statement saveQuery(T entity, EnumMap<Option.Type, Option> options) {
188 Map<ColumnMapper<?>, Object> values = new HashMap<ColumnMapper<?>, Object>();
189 boolean saveNullFields = shouldSaveNullFields(options);
190
191 for (ColumnMapper<T> cm : mapper.allColumns()) {
192 Object value = cm.getValue(entity);
193 if (cm.kind != ColumnMapper.Kind.COMPUTED && (saveNullFields || value != null)) {
194 values.put(cm, value);
195 }
196 }
197
198 BoundStatement bs = getPreparedQuery(QueryType.SAVE, values.keySet(), options).bind();
199 int i = 0;
200 for (Map.Entry<ColumnMapper<?>, Object> entry : values.entrySet()) {
201 DataType type = entry.getKey().getDataType();
202 Object value = entry.getValue();
203 bs.setBytesUnsafe(i++, value == null ? null : type.serialize(value, protocolVersion));
204 }
205
206 if (mapper.writeConsistency != null)
207 bs.setConsistencyLevel(mapper.writeConsistency);
208
209 for (Option opt : options.values()) {
210 opt.checkValidFor(QueryType.SAVE, manager);
211 opt.addToPreparedStatement(bs, i++);
212 }
213
214 return bs;
215 }
216
217 private static boolean shouldSaveNullFields(EnumMap<Option.Type, Option> options) {
218 SaveNullFields option = (SaveNullFields) options.get(SAVE_NULL_FIELDS);
219 return option == null || option.saveNullFields;
220 }
221
222 /**
223 * Save an entity mapped by this mapper.
224 * <p/>
225 * This method is basically equivalent to: {@code getManager().getSession().execute(saveQuery(entity))}.
226 *
227 * @param entity the entity to save.
228 */
229 public void save(T entity) {
230 session().execute(saveQuery(entity));
231 }
232
233 /**
234 * Save an entity mapped by this mapper and using special options for save.
235 * This method allows you to provide a suite of {@link Option} to include in
236 * the SAVE query. Options currently supported for SAVE are :
237 * <ul>
238 * <li>Timestamp</li>
239 * <li>Time-to-live (ttl)</li>
240 * <li>Consistency level</li>
241 * <li>Tracing</li>
242 * </ul>
243 *
244 * @param entity the entity to save.
245 * @param options the options object specified defining special options when saving.
246 */
247 public void save(T entity, Option... options) {
248 session().execute(saveQuery(entity, options));
249 }
250
251 /**
252 * Save an entity mapped by this mapper asynchronously.
253 * <p/>
254 * This method is basically equivalent to: {@code getManager().getSession().executeAsync(saveQuery(entity))}.
255 *
256 * @param entity the entity to save.
257 * @return a future on the completion of the save operation.
258 */
259 public ListenableFuture<Void> saveAsync(T entity) {
260 return Futures.transform(session().executeAsync(saveQuery(entity)), NOOP);
261 }
262
263 /**
264 * Save an entity mapped by this mapper asynchronously using special options for save.
265 * <p/>
266 * This method is basically equivalent to: {@code getManager().getSession().executeAsync(saveQuery(entity, options))}.
267 *
268 * @param entity the entity to save.
269 * @param options the options object specified defining special options when saving.
270 * @return a future on the completion of the save operation.
271 */
272 public ListenableFuture<Void> saveAsync(T entity, Option... options) {
273 return Futures.transform(session().executeAsync(saveQuery(entity, options)), NOOP);
274 }
275
276 /**
277 * Creates a query to fetch entity given its PRIMARY KEY.
278 * <p/>
279 * The values provided must correspond to the columns composing the PRIMARY
280 * KEY (in the order of said primary key).
281 * <p/>
282 * This method is useful if you want to setup a number of options (tracing,
283 * conistency level, ...) of the returned statement before executing it manually,
284 * but in other cases, calling {@link #get} or {@link #getAsync} is shorter.
285 * <p/>
286 * This method allows you to provide a suite of {@link Option} to include in
287 * the GET query. Options currently supported for GET are :
288 * <ul>
289 * <li>Consistency level</li>
290 * <li>Tracing</li>
291 * </ul>
292 *
293 * @param objects the primary key of the entity to fetch, or more precisely
294 * the values for the columns of said primary key in the order of the primary key.
295 * Can be followed by {@link Option} to include in the DELETE query.
296 * @return a query that fetch the entity of PRIMARY KEY {@code objects}.
297 * @throws IllegalArgumentException if the number of value provided differ from
298 * the number of columns composing the PRIMARY KEY of the mapped class, or if
299 * at least one of those values is {@code null}.
300 */
301 public Statement getQuery(Object... objects) {
302 // Order and duplicates matter for primary keys
303 List<Object> pks = new ArrayList<Object>();
304 EnumMap<Option.Type, Option> options = new EnumMap<Option.Type, Option>(defaultGetOptions);
305
306 for (Object o : objects) {
307 if (o instanceof Option) {
308 Option option = (Option) o;
309 options.put(option.type, option);
310 } else {
311 pks.add(o);
312 }
313 }
314 return getQuery(pks, options);
315 }
316
317 private Statement getQuery(List<Object> primaryKeys, EnumMap<Option.Type, Option> options) {
318
319 if (primaryKeys.size() != mapper.primaryKeySize())
320 throw new IllegalArgumentException(String.format("Invalid number of PRIMARY KEY columns provided, %d expected but got %d", mapper.primaryKeySize(), primaryKeys.size()));
321
322 BoundStatement bs = getPreparedQuery(QueryType.GET, options).bind();
323 int i = 0;
324 for (Object value : primaryKeys) {
325 ColumnMapper<T> column = mapper.getPrimaryKeyColumn(i);
326 if (value == null) {
327 throw new IllegalArgumentException(String.format("Invalid null value for PRIMARY KEY column %s (argument %d)", column.getColumnName(), i));
328 }
329 bs.setBytesUnsafe(i++, column.getDataType().serialize(value, protocolVersion));
330 }
331
332 if (mapper.readConsistency != null)
333 bs.setConsistencyLevel(mapper.readConsistency);
334
335 for (Option opt : options.values()) {
336 opt.checkValidFor(QueryType.GET, manager);
337 opt.addToPreparedStatement(bs, i);
338 if (opt.isIncludedInQuery())
339 i++;
340 }
341
342 return bs;
343 }
344
345 /**
346 * Fetch an entity based on its primary key.
347 * <p/>
348 * This method is basically equivalent to: {@code map(getManager().getSession().execute(getQuery(objects))).one()}.
349 *
350 * @param objects the primary key of the entity to fetch, or more precisely
351 * the values for the columns of said primary key in the order of the primary key.
352 * Can be followed by {@link Option} to include in the DELETE query.
353 * @return the entity fetched or {@code null} if it doesn't exist.
354 * @throws IllegalArgumentException if the number of value provided differ from
355 * the number of columns composing the PRIMARY KEY of the mapped class, or if
356 * at least one of those values is {@code null}.
357 */
358 public T get(Object... objects) {
359 return mapAliased(session().execute(getQuery(objects))).one();
360 }
361
362 /**
363 * Fetch an entity based on its primary key asynchronously.
364 * <p/>
365 * This method is basically equivalent to mapping the result of: {@code getManager().getSession().executeAsync(getQuery(objects))}.
366 *
367 * @param objects the primary key of the entity to fetch, or more precisely
368 * the values for the columns of said primary key in the order of the primary key.
369 * Can be followed by {@link Option} to include in the DELETE query.
370 * @return a future on the fetched entity. The return future will yield
371 * {@code null} if said entity doesn't exist.
372 * @throws IllegalArgumentException if the number of value provided differ from
373 * the number of columns composing the PRIMARY KEY of the mapped class, or if
374 * at least one of those values is {@code null}.
375 */
376 public ListenableFuture<T> getAsync(Object... objects) {
377 return Futures.transform(session().executeAsync(getQuery(objects)), mapOneFunction);
378 }
379
380 /**
381 * Creates a query that can be used to delete the provided entity.
382 * <p/>
383 * This method is a shortcut that extract the PRIMARY KEY from the
384 * provided entity and call {@link #deleteQuery(Object...)} with it.
385 * This method allows you to provide a suite of {@link Option} to include in
386 * the DELETE query. Note : currently, only {@link com.datastax.driver.mapping.Mapper.Option.Timestamp}
387 * is supported for DELETE queries.
388 * <p/>
389 * This method is useful if you want to setup a number of options (tracing,
390 * conistency level, ...) of the returned statement before executing it manually
391 * or need access to the {@code ResultSet} object after execution (to get the
392 * trace, the execution info, ...), but in other cases, calling {@link #delete}
393 * or {@link #deleteAsync} is shorter.
394 * <p/>
395 * This method allows you to provide a suite of {@link Option} to include in
396 * the DELETE query. Options currently supported for DELETE are :
397 * <ul>
398 * <li>Timestamp</li>
399 * <li>Consistency level</li>
400 * <li>Tracing</li>
401 * </ul>
402 *
403 * @param entity the entity to delete.
404 * @param options the options to add to the DELETE query.
405 * @return a query that delete {@code entity} (based on it's defined mapping) with
406 * provided USING options.
407 */
408 public Statement deleteQuery(T entity, Option... options) {
409 List<Object> pks = new ArrayList<Object>();
410 for (int i = 0; i < mapper.primaryKeySize(); i++) {
411 pks.add(mapper.getPrimaryKeyColumn(i).getValue(entity));
412 }
413
414 return deleteQuery(pks, toMapWithDefaults(options, defaultDeleteOptions));
415 }
416
417 /**
418 * Creates a query that can be used to delete the provided entity.
419 * <p/>
420 * This method is a shortcut that extract the PRIMARY KEY from the
421 * provided entity and call {@link #deleteQuery(Object...)} with it.
422 * <p/>
423 * This method is useful if you want to setup a number of options (tracing,
424 * conistency level, ...) of the returned statement before executing it manually
425 * or need access to the {@code ResultSet} object after execution (to get the
426 * trace, the execution info, ...), but in other cases, calling {@link #delete}
427 * or {@link #deleteAsync} is shorter.
428 *
429 * @param entity the entity to delete.
430 * @return a query that delete {@code entity} (based on it's defined mapping).
431 */
432 public Statement deleteQuery(T entity) {
433 List<Object> pks = new ArrayList<Object>();
434 for (int i = 0; i < mapper.primaryKeySize(); i++) {
435 pks.add(mapper.getPrimaryKeyColumn(i).getValue(entity));
436 }
437
438 return deleteQuery(pks, defaultDeleteOptions);
439 }
440
441 /**
442 * Creates a query that can be used to delete an entity given its PRIMARY KEY.
443 * <p/>
444 * The values provided must correspond to the columns composing the PRIMARY
445 * KEY (in the order of said primary key). The values can also contain, after
446 * specifying the primary keys columns, a suite of {@link Option} to include in
447 * the DELETE query. Note : currently, only {@link com.datastax.driver.mapping.Mapper.Option.Timestamp}
448 * is supported for DELETE queries.
449 * <p/>
450 * This method is useful if you want to setup a number of options (tracing,
451 * conistency level, ...) of the returned statement before executing it manually
452 * or need access to the {@code ResultSet} object after execution (to get the
453 * trace, the execution info, ...), but in other cases, calling {@link #delete}
454 * or {@link #deleteAsync} is shorter.
455 * This method allows you to provide a suite of {@link Option} to include in
456 * the DELETE query. Options currently supported for DELETE are :
457 * <ul>
458 * <li>Timestamp</li>
459 * <li>Consistency level</li>
460 * <li>Tracing</li>
461 * </ul>
462 *
463 * @param objects the primary key of the entity to delete, or more precisely
464 * the values for the columns of said primary key in the order of the primary key.
465 * Can be followed by {@link Option} to include in the DELETE
466 * query.
467 * @return a query that delete the entity of PRIMARY KEY {@code primaryKey}.
468 * @throws IllegalArgumentException if the number of value provided differ from
469 * the number of columns composing the PRIMARY KEY of the mapped class, or if
470 * at least one of those values is {@code null}.
471 */
472 public Statement deleteQuery(Object... objects) {
473 // Order and duplicates matter for primary keys
474 List<Object> pks = new ArrayList<Object>();
475 EnumMap<Option.Type, Option> options = new EnumMap<Option.Type, Option>(defaultDeleteOptions);
476
477 for (Object o : objects) {
478 if (o instanceof Option) {
479 Option option = (Option) o;
480 options.put(option.type, option);
481 } else {
482 pks.add(o);
483 }
484 }
485 return deleteQuery(pks, options);
486 }
487
488 private Statement deleteQuery(List<Object> primaryKey, EnumMap<Option.Type, Option> options) {
489 if (primaryKey.size() != mapper.primaryKeySize())
490 throw new IllegalArgumentException(String.format("Invalid number of PRIMARY KEY columns provided, %d expected but got %d", mapper.primaryKeySize(), primaryKey.size()));
491
492 BoundStatement bs = getPreparedQuery(QueryType.DEL, options).bind();
493
494 if (mapper.writeConsistency != null)
495 bs.setConsistencyLevel(mapper.writeConsistency);
496
497 int i = 0;
498 for (Option opt : options.values()) {
499 opt.checkValidFor(QueryType.DEL, manager);
500 opt.addToPreparedStatement(bs, i);
501 if (opt.isIncludedInQuery())
502 i++;
503 }
504
505 int columnNumber = 0;
506 for (Object value : primaryKey) {
507 ColumnMapper<T> column = mapper.getPrimaryKeyColumn(columnNumber);
508 if (value == null) {
509 throw new IllegalArgumentException(String.format("Invalid null value for PRIMARY KEY column %s (argument %d)", column.getColumnName(), i));
510 }
511 bs.setBytesUnsafe(i++, column.getDataType().serialize(value, protocolVersion));
512 columnNumber++;
513 }
514 return bs;
515 }
516
517 /**
518 * Deletes an entity mapped by this mapper.
519 * <p/>
520 * This method is basically equivalent to: {@code getManager().getSession().execute(deleteQuery(entity))}.
521 *
522 * @param entity the entity to delete.
523 */
524 public void delete(T entity) {
525 session().execute(deleteQuery(entity));
526 }
527
528 /**
529 * Deletes an entity mapped by this mapper using provided options.
530 * <p/>
531 * This method is basically equivalent to: {@code getManager().getSession().execute(deleteQuery(entity, options))}.
532 *
533 * @param entity the entity to delete.
534 * @param options the options to add to the DELETE query.
535 */
536 public void delete(T entity, Option... options) {
537 session().execute(deleteQuery(entity, options));
538 }
539
540 /**
541 * Deletes an entity mapped by this mapper asynchronously.
542 * <p/>
543 * This method is basically equivalent to: {@code getManager().getSession().executeAsync(deleteQuery(entity))}.
544 *
545 * @param entity the entity to delete.
546 * @return a future on the completion of the deletion.
547 */
548 public ListenableFuture<Void> deleteAsync(T entity) {
549 return Futures.transform(session().executeAsync(deleteQuery(entity)), NOOP);
550 }
551
552 /**
553 * Deletes an entity mapped by this mapper asynchronously using provided options.
554 * <p/>
555 * This method is basically equivalent to: {@code getManager().getSession().executeAsync(deleteQuery(entity, options))}.
556 *
557 * @param entity the entity to delete.
558 * @param options the options to add to the DELETE query.
559 * @return a future on the completion of the deletion.
560 */
561 public ListenableFuture<Void> deleteAsync(T entity, Option... options) {
562 return Futures.transform(session().executeAsync(deleteQuery(entity, options)), NOOP);
563 }
564
565 /**
566 * Deletes an entity based on its primary key.
567 * <p/>
568 * This method is basically equivalent to: {@code getManager().getSession().execute(deleteQuery(objects))}.
569 *
570 * @param objects the primary key of the entity to delete, or more precisely
571 * the values for the columns of said primary key in the order
572 * of the primary key.Can be followed by {@link Option} to include
573 * in the DELETE query.
574 * @throws IllegalArgumentException if the number of value provided differ from
575 * the number of columns composing the PRIMARY KEY of the mapped class, or if
576 * at least one of those values is {@code null}.
577 */
578 public void delete(Object... objects) {
579 session().execute(deleteQuery(objects));
580 }
581
582 /**
583 * Deletes an entity based on its primary key asynchronously.
584 * <p/>
585 * This method is basically equivalent to: {@code getManager().getSession().executeAsync(deleteQuery(objects))}.
586 *
587 * @param objects the primary key of the entity to delete, or more precisely
588 * the values for the columns of said primary key in the order
589 * of the primary key. Can be followed by {@link Option} to include
590 * in the DELETE query.
591 * @throws IllegalArgumentException if the number of value provided differ from
592 * the number of columns composing the PRIMARY KEY of the mapped class, or if
593 * at least one of those values is {@code null}.
594 */
595 public ListenableFuture<Void> deleteAsync(Object... objects) {
596 return Futures.transform(session().executeAsync(deleteQuery(objects)), NOOP);
597 }
598
599 /**
600 * Maps the rows from a {@code ResultSet} into the class this is a mapper of.
601 * <p/>
602 * Use this method to map a result set that was not generated by the mapper (e.g. a result set coming from a
603 * manual query or an {@link Accessor method}.
604 * It expects that the result set contains all column mapped in the target class,
605 * and that they are not aliased. {@link Computed} fields will not be filled in mapped objects.
606 *
607 * @param resultSet the {@code ResultSet} to map.
608 * @return the mapped result set. Note that the returned mapped result set
609 * will encapsulate {@code resultSet} and so consuming results from this
610 * returned mapped result set will consume results from {@code resultSet}
611 * and vice-versa.
612 * @see #mapAliased(ResultSet)
613 */
614 public Result<T> map(ResultSet resultSet) {
615 return new Result<T>(resultSet, mapper, protocolVersion);
616 }
617
618 /**
619 * Maps the rows from a {@code ResultSet} into the class this is a mapper of.
620 * <p/>
621 * Use this method to map a result set coming from the execution of the {@code Statement} returned by
622 * {@link #getQuery(Object...)}. {@link Computed} fields will be filled in the mapped object.
623 *
624 * @param resultSet the {@code ResultSet} to map.
625 * @return the mapped result set. Note that the returned mapped result set
626 * will encapsulate {@code resultSet} and so consuming results from this
627 * returned mapped result set will consume results from {@code resultSet}
628 * and vice-versa.
629 * @see #map(ResultSet)
630 */
631 public Result<T> mapAliased(ResultSet resultSet) {
632 return (manager.isCassandraV1)
633 ? map(resultSet) // no aliases
634 : new Result<T>(resultSet, mapper, protocolVersion, true);
635 }
636
637 /**
638 * Set the default save {@link Option} for this object mapper, that will be used
639 * in all save operations unless overridden. Refer to {@link Mapper#save(Object, Option...)})}
640 * to check available save options.
641 *
642 * @param options the options to set. To reset, use {@link Mapper#resetDefaultSaveOptions}.
643 */
644 public void setDefaultSaveOptions(Option... options) {
645 this.defaultSaveOptions = toMap(options);
646 }
647
648 /**
649 * Reset the default save options for this object mapper.
650 */
651 public void resetDefaultSaveOptions() {
652 this.defaultSaveOptions = NO_OPTIONS;
653 }
654
655 /**
656 * Set the default get {@link Option} for this object mapper, that will be used
657 * in all get operations unless overridden. Refer to {@link Mapper#get(Object...)} )} to check available
658 * get options.
659 *
660 * @param options the options to set. To reset, use {@link Mapper#resetDefaultGetOptions}.
661 */
662 public void setDefaultGetOptions(Option... options) {
663 this.defaultGetOptions = toMap(options);
664
665 }
666
667 /**
668 * Reset the default save options for this object mapper.
669 */
670 public void resetDefaultGetOptions() {
671 this.defaultGetOptions = NO_OPTIONS;
672 }
673
674 /**
675 * Set the default delete {@link Option} for this object mapper, that will be used
676 * in all delete operations unless overridden. Refer to {@link Mapper#delete(Object...)} )}
677 * to check available delete options.
678 *
679 * @param options the options to set. To reset, use {@link Mapper#resetDefaultDeleteOptions}.
680 */
681 public void setDefaultDeleteOptions(Option... options) {
682 this.defaultDeleteOptions = toMap(options);
683 }
684
685 /**
686 * Reset the default delete options for this object mapper.
687 */
688 public void resetDefaultDeleteOptions() {
689 this.defaultDeleteOptions = NO_OPTIONS;
690 }
691
692 private static EnumMap<Option.Type, Option> toMap(Option[] options) {
693 EnumMap<Option.Type, Option> result = new EnumMap<Option.Type, Option>(Option.Type.class);
694 for (Option option : options) {
695 result.put(option.type, option);
696 }
697 return result;
698 }
699
700 private static EnumMap<Option.Type, Option> toMapWithDefaults(Option[] options, EnumMap<Option.Type, Option> defaults) {
701 EnumMap<Option.Type, Option> result = new EnumMap<Option.Type, Option>(defaults);
702 for (Option option : options) {
703 result.put(option.type, option);
704 }
705 return result;
706 }
707
708 /**
709 * An option for a mapper operation.
710 * <p/>
711 * Options can be passed to individual operations:
712 * <pre>
713 * mapper.save(myObject, Option.ttl(3600));
714 * </pre>
715 * <p/>
716 * The mapper can also have defaults, that will apply to all operations that do not
717 * override these particular option:
718 * <pre>
719 * mapper.setDefaultSaveOptions(Option.ttl(3600));
720 * mapper.save(myObject);
721 * </pre>
722 * <p/>
723 * <p/>
724 * See the static methods in this class for available options.
725 */
726 public static abstract class Option {
727
728 enum Type {TTL, TIMESTAMP, CL, TRACING, SAVE_NULL_FIELDS}
729
730 final Type type;
731
732 protected Option(Type type) {
733 this.type = type;
734 }
735
736 /**
737 * Creates a new Option object to add time-to-live to a mapper operation. This is
738 * only valid for save operations.
739 * <p/>
740 * Note that this option is only available if using {@link ProtocolVersion#V2} or above.
741 *
742 * @param ttl the TTL (in seconds).
743 * @return the option.
744 */
745 public static Option ttl(int ttl) {
746 return new Ttl(ttl);
747 }
748
749 /**
750 * Creates a new Option object to add a timestamp to a mapper operation. This is
751 * only valid for save and delete operations.
752 * <p/>
753 * Note that this option is only available if using {@link ProtocolVersion#V2} or above.
754 *
755 * @param timestamp the timestamp (in microseconds).
756 * @return the option.
757 */
758 public static Option timestamp(long timestamp) {
759 return new Timestamp(timestamp);
760 }
761
762 /**
763 * Creates a new Option object to add a consistency level value to a mapper operation. This
764 * is valid for save, delete and get operations.
765 * <p/>
766 * Note that the consistency level can also be defined at the mapper level, as a parameter
767 * of the {@link com.datastax.driver.mapping.annotations.Table} annotation (this is redundant
768 * for backward compatibility). This option, whether defined on a specific call or as the
769 * default, will always take precedence over the annotation.
770 *
771 * @param cl the {@link com.datastax.driver.core.ConsistencyLevel} to use for the operation.
772 * @return the option.
773 */
774 public static Option consistencyLevel(ConsistencyLevel cl) {
775 return new ConsistencyLevelOption(cl);
776 }
777
778 /**
779 * Creates a new Option object to enable query tracing for a mapper operation. This
780 * is valid for save, delete and get operations.
781 *
782 * @param enabled whether to enable tracing.
783 * @return the option.
784 */
785 public static Option tracing(boolean enabled) {
786 return new Tracing(enabled);
787 }
788
789 /**
790 * Creates a new Option object to specify whether null entity fields should be included in
791 * insert queries. This option is valid only for save operations.
792 * <p/>
793 * If this option is not specified, it defaults to {@code true} (null fields are saved).
794 *
795 * @param enabled whether to include null fields in queries.
796 * @return the option.
797 */
798 public static Option saveNullFields(boolean enabled) {
799 return new SaveNullFields(enabled);
800 }
801
802 public Type getType() {
803 return this.type;
804 }
805
806 abstract void appendTo(Insert.Options usings);
807
808 abstract void appendTo(Delete.Options usings);
809
810 abstract void addToPreparedStatement(BoundStatement bs, int i);
811
812 abstract void checkValidFor(QueryType qt, MappingManager manager) throws IllegalArgumentException;
813
814 abstract boolean isIncludedInQuery();
815
816 static class Ttl extends Option {
817
818 private int ttlValue;
819
820 Ttl(int value) {
821 super(Type.TTL);
822 this.ttlValue = value;
823 }
824
825 void appendTo(Insert.Options usings) {
826 usings.and(QueryBuilder.ttl(QueryBuilder.bindMarker()));
827 }
828
829 @Override
830 void appendTo(Delete.Options usings) {
831 throw new UnsupportedOperationException("shouldn't be called");
832 }
833
834 @Override
835 void addToPreparedStatement(BoundStatement bs, int i) {
836 bs.setInt(i, this.ttlValue);
837 }
838
839 @Override
840 void checkValidFor(QueryType qt, MappingManager manager) {
841 checkArgument(!manager.isCassandraV1, "TTL option requires native protocol v2 or above");
842 checkArgument(qt == QueryType.SAVE, "TTL option is only allowed in save queries");
843 }
844
845 @Override
846 boolean isIncludedInQuery() {
847 return true;
848 }
849 }
850
851 static class Timestamp extends Option {
852
853 private long tsValue;
854
855 Timestamp(long value) {
856 super(Type.TIMESTAMP);
857 this.tsValue = value;
858 }
859
860 @Override
861 void appendTo(Insert.Options usings) {
862 usings.and(QueryBuilder.timestamp(QueryBuilder.bindMarker()));
863 }
864
865 @Override
866 void appendTo(Delete.Options usings) {
867 usings.and(QueryBuilder.timestamp(QueryBuilder.bindMarker()));
868 }
869
870 @Override
871 void checkValidFor(QueryType qt, MappingManager manager) {
872 checkArgument(!manager.isCassandraV1, "Timestamp option requires native protocol v2 or above");
873 checkArgument(qt == QueryType.SAVE || qt == QueryType.DEL, "Timestamp option is only allowed in save and delete queries");
874 }
875
876 @Override
877 void addToPreparedStatement(BoundStatement bs, int i) {
878 bs.setLong(i, this.tsValue);
879 }
880
881 @Override
882 boolean isIncludedInQuery() {
883 return true;
884 }
885 }
886
887 static class ConsistencyLevelOption extends Option {
888
889 private ConsistencyLevel cl;
890
891 ConsistencyLevelOption(ConsistencyLevel cl) {
892 super(Type.CL);
893 this.cl = cl;
894 }
895
896 @Override
897 void appendTo(Insert.Options usings) {
898 throw new UnsupportedOperationException("shouldn't be called");
899 }
900
901 @Override
902 void appendTo(Delete.Options usings) {
903 throw new UnsupportedOperationException("shouldn't be called");
904 }
905
906 @Override
907 void addToPreparedStatement(BoundStatement bs, int i) {
908 bs.setConsistencyLevel(cl);
909 }
910
911 @Override
912 void checkValidFor(QueryType qt, MappingManager manager) {
913 checkArgument(qt == QueryType.SAVE || qt == QueryType.DEL || qt == QueryType.GET,
914 "Consistency level option is only allowed in save, delete and get queries");
915 }
916
917 @Override
918 boolean isIncludedInQuery() {
919 return false;
920 }
921 }
922
923 static class Tracing extends Option {
924
925 private boolean tracing;
926
927 Tracing(boolean tracing) {
928 super(Type.TRACING);
929 this.tracing = tracing;
930 }
931
932 @Override
933 void appendTo(Insert.Options usings) {
934 throw new UnsupportedOperationException("shouldn't be called");
935 }
936
937 @Override
938 void appendTo(Delete.Options usings) {
939 throw new UnsupportedOperationException("shouldn't be called");
940 }
941
942 @Override
943 void addToPreparedStatement(BoundStatement bs, int i) {
944 if (this.tracing)
945 bs.enableTracing();
946 }
947
948 @Override
949 void checkValidFor(QueryType qt, MappingManager manager) {
950 checkArgument(qt == QueryType.SAVE || qt == QueryType.DEL || qt == QueryType.GET,
951 "Tracing option is only allowed in save, delete and get queries");
952 }
953
954 @Override
955 boolean isIncludedInQuery() {
956 return false;
957 }
958 }
959
960 static class SaveNullFields extends Option {
961
962 private boolean saveNullFields;
963
964 SaveNullFields(boolean saveNullFields) {
965 super(SAVE_NULL_FIELDS);
966 this.saveNullFields = saveNullFields;
967 }
968
969 @Override
970 void appendTo(Insert.Options usings) {
971 throw new UnsupportedOperationException("shouldn't be called");
972 }
973
974 @Override
975 void appendTo(Delete.Options usings) {
976 throw new UnsupportedOperationException("shouldn't be called");
977 }
978
979 @Override
980 void addToPreparedStatement(BoundStatement bs, int i) {
981 // nothing to do
982 }
983
984 @Override
985 void checkValidFor(QueryType qt, MappingManager manager) {
986 checkArgument(qt == QueryType.SAVE, "SaveNullFields option is only allowed in save queries");
987 }
988
989 @Override
990 boolean isIncludedInQuery() {
991 return false;
992 }
993 }
994
995 }
996
997 private static class MapperQueryKey {
998 private final QueryType queryType;
999 private final EnumSet<Option.Type> optionTypes;
1000 private final Set<ColumnMapper<?>> columns;
1001
1002 MapperQueryKey(QueryType queryType, Set<ColumnMapper<?>> columnMappers, EnumMap<Option.Type, Option> options) {
1003 Preconditions.checkNotNull(queryType);
1004 Preconditions.checkNotNull(options);
1005 Preconditions.checkNotNull(columnMappers);
1006 this.queryType = queryType;
1007 this.columns = columnMappers;
1008 this.optionTypes = EnumSet.noneOf(Option.Type.class);
1009 for (Option opt : options.values()) {
1010 if (opt.isIncludedInQuery())
1011 this.optionTypes.add(opt.type);
1012 }
1013 }
1014
1015 @Override
1016 public boolean equals(Object other) {
1017 if (this == other)
1018 return true;
1019 if (other instanceof MapperQueryKey) {
1020 MapperQueryKey that = (MapperQueryKey) other;
1021 return this.queryType.equals(that.queryType)
1022 && this.optionTypes.equals(that.optionTypes)
1023 && this.columns.equals(that.columns);
1024 }
1025 return false;
1026 }
1027
1028 public int hashCode() {
1029 return Objects.hashCode(queryType, optionTypes, columns);
1030 }
1031 }
1032}