Elffuss BraidHub

kikocis/java-driver public

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