Elffuss BraidHub

kikocis/java-driver public

e02defd2efe5 · 15.0 KiBRawPermalink
1/*
2 * Copyright (C) 2012-2014 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.Collections;
19import java.util.HashMap;
20import java.util.Map;
21
22import com.google.common.base.Function;
23import com.google.common.base.Functions;
24import com.google.common.util.concurrent.Futures;
25import com.google.common.util.concurrent.ListenableFuture;
26
27import org.slf4j.Logger;
28import org.slf4j.LoggerFactory;
29
30import com.datastax.driver.core.*;
31
32/**
33 * An object handling the mapping of a particular class.
34 * <p>
35 * A {@code Mapper} object is obtained from a {@code MappingManager} using the
36 * {@link MappingManager#mapper} method.
37 */
38public class Mapper<T> {
39
40 private static final Logger logger = LoggerFactory.getLogger(EntityMapper.class);
41
42 final MappingManager manager;
43 final ProtocolVersion protocolVersion;
44 final Class<T> klass;
45 final EntityMapper<T> mapper;
46 final TableMetadata tableMetadata;
47
48 // Cache prepared statements for each type of query we use.
49 private volatile Map<QueryType, PreparedStatement> preparedQueries = Collections.<QueryType, PreparedStatement>emptyMap();
50
51 private static final Function<Object, Void> NOOP = Functions.<Void>constant(null);
52
53 final Function<ResultSet, T> mapOneFunction;
54 final Function<ResultSet, Result<T>> mapAllFunction;
55
56 Mapper(MappingManager manager, Class<T> klass, EntityMapper<T> mapper) {
57 this.manager = manager;
58 this.klass = klass;
59 this.mapper = mapper;
60
61 KeyspaceMetadata keyspace = session().getCluster().getMetadata().getKeyspace(mapper.getKeyspace());
62 this.tableMetadata = keyspace == null ? null : keyspace.getTable(Metadata.quote(mapper.getTable()));
63
64 this.protocolVersion = manager.getSession().getCluster().getConfiguration().getProtocolOptions().getProtocolVersionEnum();
65 this.mapOneFunction = new Function<ResultSet, T>() {
66 public T apply(ResultSet rs) {
67 return Mapper.this.map(rs).one();
68 }
69 };
70 this.mapAllFunction = new Function<ResultSet, Result<T>>() {
71 public Result<T> apply(ResultSet rs) {
72 return Mapper.this.map(rs);
73 }
74 };
75 }
76
77 Session session() {
78 return manager.getSession();
79 }
80
81 PreparedStatement getPreparedQuery(QueryType type) {
82 PreparedStatement stmt = preparedQueries.get(type);
83 if (stmt == null) {
84 synchronized (preparedQueries) {
85 stmt = preparedQueries.get(type);
86 if (stmt == null) {
87 String query = type.makePreparedQueryString(tableMetadata, mapper);
88 logger.debug("Preparing query {}", query);
89 stmt = session().prepare(query);
90 Map<QueryType, PreparedStatement> newQueries = new HashMap<QueryType, PreparedStatement>(preparedQueries);
91 newQueries.put(type, stmt);
92 preparedQueries = newQueries;
93 }
94 }
95 }
96 return stmt;
97 }
98
99 /**
100 * The {@code MappingManager} managing this mapper.
101 *
102 * @return the {@code MappingManager} managing this mapper.
103 */
104 public MappingManager getManager() {
105 return manager;
106 }
107
108 /**
109 * Creates a query that can be used to save the provided entity.
110 * <p>
111 * This method is useful if you want to setup a number of options (tracing,
112 * conistency level, ...) of the returned statement before executing it manually
113 * or need access to the {@code ResultSet} object after execution (to get the
114 * trace, the execution info, ...), but in other cases, calling {@link #save}
115 * or {@link #saveAsync} is shorter.
116 *
117 * @param entity the entity to save.
118 * @return a query that saves {@code entity} (based on it's defined mapping).
119 */
120 public Statement saveQuery(T entity) {
121 PreparedStatement ps = getPreparedQuery(QueryType.SAVE);
122
123 BoundStatement bs = ps.bind();
124 int i = 0;
125 for (ColumnMapper<T> cm : mapper.allColumns()) {
126 Object value = cm.getValue(entity);
127 bs.setBytesUnsafe(i++, value == null ? null : cm.getDataType().serialize(value, protocolVersion));
128 }
129
130 if (mapper.writeConsistency != null)
131 bs.setConsistencyLevel(mapper.writeConsistency);
132 return bs;
133 }
134
135 /**
136 * Save an entity mapped by this mapper.
137 * <p>
138 * This method is basically equivalent to: {@code getManager().getSession().execute(saveQuery(entity))}.
139 *
140 * @param entity the entity to save.
141 */
142 public void save(T entity) {
143 session().execute(saveQuery(entity));
144 }
145
146 /**
147 * Save an entity mapped by this mapper asynchonously.
148 * <p>
149 * This method is basically equivalent to: {@code getManager().getSession().executeAsync(saveQuery(entity))}.
150 *
151 * @param entity the entity to save.
152 * @return a future on the completion of the save operation.
153 */
154 public ListenableFuture<Void> saveAsync(T entity) {
155 return Futures.transform(session().executeAsync(saveQuery(entity)), NOOP);
156 }
157
158 /**
159 * Creates a query that can be used to delete the provided entity.
160 * <p>
161 * This method is a shortcut that extract the PRIMARY KEY from the
162 * provided entity and call {@link #deleteQuery(Object...)} with it.
163 * <p>
164 * This method is useful if you want to setup a number of options (tracing,
165 * conistency level, ...) of the returned statement before executing it manually
166 * or need access to the {@code ResultSet} object after execution (to get the
167 * trace, the execution info, ...), but in other cases, calling {@link #delete}
168 * or {@link #deleteAsync} is shorter.
169 *
170 * @param entity the entity to delete.
171 * @return a query that delete {@code entity} (based on it's defined mapping).
172 */
173 public Statement deleteQuery(T entity) {
174 Object[] pks = new Object[mapper.primaryKeySize()];
175 for (int i = 0; i < pks.length; i++)
176 pks[i] = mapper.getPrimaryKeyColumn(i).getValue(entity);
177
178 return deleteQuery(pks);
179 }
180
181 /**
182 * Creates a query that can be used to delete an entity given its PRIMARY KEY.
183 * <p>
184 * The values provided must correspond to the columns composing the PRIMARY
185 * KEY (in the order of said primary key).
186 * <p>
187 * This method is useful if you want to setup a number of options (tracing,
188 * conistency level, ...) of the returned statement before executing it manually
189 * or need access to the {@code ResultSet} object after execution (to get the
190 * trace, the execution info, ...), but in other cases, calling {@link #delete}
191 * or {@link #deleteAsync} is shorter.
192 *
193 * @param primaryKey the primary key of the entity to delete, or more precisely
194 * the values for the columns of said primary key in the order of the primary key.
195 * @return a query that delete the entity of PRIMARY KEY {@code primaryKey}.
196 *
197 * @throws IllegalArgumentException if the number of value provided differ from
198 * the number of columns composing the PRIMARY KEY of the mapped class, or if
199 * at least one of those values is {@code null}.
200 */
201 public Statement deleteQuery(Object...primaryKey) {
202 if (primaryKey.length != mapper.primaryKeySize())
203 throw new IllegalArgumentException(String.format("Invalid number of PRIMARY KEY columns provided, %d expected but got %d", mapper.primaryKeySize(), primaryKey.length));
204
205 PreparedStatement ps = getPreparedQuery(QueryType.DEL);
206
207 BoundStatement bs = ps.bind();
208 for (int i = 0; i < primaryKey.length; i++) {
209 ColumnMapper<T> column = mapper.getPrimaryKeyColumn(i);
210 Object value = primaryKey[i];
211 if (value == null)
212 throw new IllegalArgumentException(String.format("Invalid null value for PRIMARY KEY column %s (argument %d)", column.getColumnName(), i));
213 bs.setBytesUnsafe(i, column.getDataType().serialize(value, protocolVersion));
214 }
215
216 if (mapper.writeConsistency != null)
217 bs.setConsistencyLevel(mapper.writeConsistency);
218 return bs;
219 }
220
221 /**
222 * Deletes an entity mapped by this mapper.
223 * <p>
224 * This method is basically equivalent to: {@code getManager().getSession().execute(deleteQuery(entity))}.
225 *
226 * @param entity the entity to delete.
227 */
228 public void delete(T entity) {
229 session().execute(deleteQuery(entity));
230 }
231
232 /**
233 * Deletes an entity mapped by this mapper asynchronously.
234 * <p>
235 * This method is basically equivalent to: {@code getManager().getSession().executeAsync(deleteQuery(entity))}.
236 *
237 * @param entity the entity to delete.
238 * @return a future on the completion of the deletion.
239 */
240 public ListenableFuture<Void> deleteAsync(T entity) {
241 return Futures.transform(session().executeAsync(deleteQuery(entity)), NOOP);
242 }
243
244 /**
245 * Deletes an entity based on its primary key.
246 * <p>
247 * This method is basically equivalent to: {@code getManager().getSession().execute(deleteQuery(primaryKey))}.
248 *
249 * @param primaryKey the primary key of the entity to delete, or more precisely
250 * the values for the columns of said primary key in the order of the primary key.
251 *
252 * @throws IllegalArgumentException if the number of value provided differ from
253 * the number of columns composing the PRIMARY KEY of the mapped class, or if
254 * at least one of those values is {@code null}.
255 */
256 public void delete(Object... primaryKey) {
257 session().execute(deleteQuery(primaryKey));
258 }
259
260 /**
261 * Deletes an entity based on its primary key asynchronously.
262 * <p>
263 * This method is basically equivalent to: {@code getManager().getSession().executeAsync(deleteQuery(primaryKey))}.
264 *
265 * @param primaryKey the primary key of the entity to delete, or more precisely
266 * the values for the columns of said primary key in the order of the primary key.
267 * @return a future on the completion of the deletion.
268 *
269 * @throws IllegalArgumentException if the number of value provided differ from
270 * the number of columns composing the PRIMARY KEY of the mapped class, or if
271 * at least one of those values is {@code null}.
272 */
273 public ListenableFuture<Void> deleteAsync(Object... primaryKey) {
274 return Futures.transform(session().executeAsync(deleteQuery(primaryKey)), NOOP);
275 }
276
277 /**
278 * Map the rows from a {@code ResultSet} into the class this is mapper of.
279 *
280 * @param resultSet the {@code ResultSet} to map.
281 * @return the mapped result set. Note that the returned mapped result set
282 * will encapsulate {@code resultSet} and so consuming results from this
283 * returned mapped result set will consume results from {@code resultSet}
284 * and vice-versa.
285 */
286 public Result<T> map(ResultSet resultSet) {
287 return new Result<T>(resultSet, mapper, protocolVersion);
288 }
289
290 /**
291 * Creates a query to fetch entity given its PRIMARY KEY.
292 * <p>
293 * The values provided must correspond to the columns composing the PRIMARY
294 * KEY (in the order of said primary key).
295 * <p>
296 * This method is useful if you want to setup a number of options (tracing,
297 * conistency level, ...) of the returned statement before executing it manually,
298 * but in other cases, calling {@link #get} or {@link #getAsync} is shorter.
299 *
300 * @param primaryKey the primary key of the entity to fetch, or more precisely
301 * the values for the columns of said primary key in the order of the primary key.
302 * @return a query that fetch the entity of PRIMARY KEY {@code primaryKey}.
303 *
304 * @throws IllegalArgumentException if the number of value provided differ from
305 * the number of columns composing the PRIMARY KEY of the mapped class, or if
306 * at least one of those values is {@code null}.
307 */
308 public Statement getQuery(Object... primaryKey) {
309 if (primaryKey.length != mapper.primaryKeySize())
310 throw new IllegalArgumentException(String.format("Invalid number of PRIMARY KEY columns provided, %d expected but got %d", mapper.primaryKeySize(), primaryKey.length));
311
312 PreparedStatement ps = getPreparedQuery(QueryType.GET);
313
314 BoundStatement bs = ps.bind();
315 for (int i = 0; i < primaryKey.length; i++) {
316 ColumnMapper<T> column = mapper.getPrimaryKeyColumn(i);
317 Object value = primaryKey[i];
318 if (value == null)
319 throw new IllegalArgumentException(String.format("Invalid null value for PRIMARY KEY column %s (argument %d)", column.getColumnName(), i));
320 bs.setBytesUnsafe(i, column.getDataType().serialize(value, protocolVersion));
321 }
322
323 if (mapper.readConsistency != null)
324 bs.setConsistencyLevel(mapper.readConsistency);
325 return bs;
326 }
327
328 /**
329 * Fetch an entity based on its primary key.
330 * <p>
331 * This method is basically equivalent to: {@code map(getManager().getSession().execute(getQuery(primaryKey))).one()}.
332 *
333 * @param primaryKey the primary key of the entity to fetch, or more precisely
334 * the values for the columns of said primary key in the order of the primary key.
335 * @return the entity fetched or {@code null} if it doesn't exist.
336 *
337 * @throws IllegalArgumentException if the number of value provided differ from
338 * the number of columns composing the PRIMARY KEY of the mapped class, or if
339 * at least one of those values is {@code null}.
340 */
341 public T get(Object... primaryKey) {
342 return map(session().execute(getQuery(primaryKey))).one();
343 }
344
345 /**
346 * Fetch an entity based on its primary key asynchronously.
347 * <p>
348 * This method is basically equivalent to mapping the result of: {@code getManager().getSession().executeAsync(getQuery(primaryKey))}.
349 *
350 * @param primaryKey the primary key of the entity to fetch, or more precisely
351 * the values for the columns of said primary key in the order of the primary key.
352 * @return a future on the fetched entity. The return future will yield
353 * {@code null} if said entity doesn't exist.
354 *
355 * @throws IllegalArgumentException if the number of value provided differ from
356 * the number of columns composing the PRIMARY KEY of the mapped class, or if
357 * at least one of those values is {@code null}.
358 */
359 public ListenableFuture<T> getAsync(Object... primaryKey) {
360 return Futures.transform(session().executeAsync(getQuery(primaryKey)), mapOneFunction);
361 }
362}