Elffuss BraidHub

kikocis/java-driver public

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