Elffuss BraidHub

kikocis/java-driver public

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