Elffuss BraidHub

kikocis/java-driver public

3.1.x · 9.7 KiBRenderedRawPermalink
1## Using the mapper
2
3First, create a [MappingManager]. It wraps an existing [Session]
4instance:
5
6```java
7MappingManager manager = new MappingManager(session);
8```
9
10`MappingManager` is thread-safe and can be safely shared throughout your
11application. You would typically create one instance at startup, right
12after your `Session`.
13
14Note that `MappingManager` will initialize the `Session` if not
15previously done (this was not the case in previous driver versions; if
16this is a problem for you, see `MappingManager(session, protocolVersion)`).
17
18### Entity mappers
19
20Each entity class (annotated with `@Table`) is managed by a dedicated
21[Mapper] object. You obtain this object from the `MappingManager`:
22
23```java
24Mapper<User> mapper = manager.mapper(User.class);
25```
26
27`Mapper` objects are thread-safe. The manager caches them internally, so
28calling `manager#mapper` more than once for the same class will return
29the previously generated mapper.
30
31[Mapper]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/mapping/Mapper.html
32[MappingManager]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/mapping/MappingManager.html
33[Session]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/Session.html
34
35#### Basic CRUD operations
36
37To save an object, use `Mapper#save`:
38
39```java
40UUID userId = ...;
41User u = new User(userId, "John Doe", new Address("street", 01000));
42mapper.save(u);
43```
44
45--------------
46
47To retrieve an object, use `Mapper#get`:
48
49```java
50UUID userId = ...;
51User u = mapper.get(userId);
52```
53
54`get`'s arguments must match the partition key components (number of
55arguments and their types).
56
57--------------
58
59To delete a row in a table, use `Mapper#delete`. This method support
60deleting a row given either its primary keys, or the object to delete:
61
62```java
63UUID userId = ...;
64mapper.delete(userId);
65mapper.delete(u);
66```
67
68--------------
69
70All these CRUD operations are synchronous, but the `Mapper` provides
71their asynchronous equivalents:
72
73```java
74ListenableFuture<Void> saveFuture = mapper.saveAsync(u);
75ListenableFuture<User> userFuture = mapper.getAsync(userId);
76ListenableFuture<Void> deleteFuture = mapper.deleteAsync(userId);
77```
78
79#### Mapper options
80
81The basic CRUD operations accept additional options to customize the
82underlying query:
83
84- `ttl`: add a time-to-live value for the operation.
85- `timestamp`: add a timestamp value for the operation.
86- `consistencyLevel`: specify a consistency level.
87- `tracing`: set tracing flag for the query.
88- `saveNullFields`: if set to true, fields with value `null` in an
89 instance that is to be persisted will be explicitly written as `null`
90 in the query. If set to false, fields with null value won't be included
91 in the write query (thus avoiding tombstones). If not specified, the
92 default behavior is to persist `null` fields.
93
94To use options, add them to the mapper call after regular parameters:
95
96```java
97import static com.datastax.driver.mapping.Mapper.Option.*;
98
99mapper.save(new User(userId, "helloworld"),
100 timestamp(123456L), tracing(true), ttl(42));
101```
102
103Some options don't apply to all operations:
104
105<table border="1" style="text-align:center; width:100%;margin-bottom:1em;">
106 <tr> <td><b>Option</b></td> <td><b>save/saveQuery</b></td> <td><b>get/getQuery</b></td> <td><b>delete/deleteQuery</b></td></tr>
107 <tr> <td>Ttl</td> <td>yes</td> <td>no</td> <td>no</td> </tr>
108 <tr> <td>Timestamp</td> <td>yes</td> <td>no</td> <td>yes</td> </tr>
109 <tr> <td>ConsistencyLevel</td> <td>yes</td> <td>yes</td> <td>yes</td> </tr>
110 <tr> <td>Tracing</td> <td>yes</td> <td>yes</td> <td>yes</td> </tr>
111 <tr> <td>SaveNullFields</td> <td>yes</td> <td>no</td> <td>no</td> </tr>
112</table>
113
114Note that `Option.consistencyLevel` is redundant with the consistency
115level defined by [@Table](../creating/#creating-a-table-entity).
116If both are defined, the option will take precedence over the
117annotation.
118
119Default options can be defined for each type of operation:
120
121```java
122mapper.setDefaultGetOption(tracing(true), consistencyLevel(QUORUM));
123mapper.setDefaultSaveOption(saveNullFields(false));
124mapper.setDefaultDeleteOption(consistencyLevel(ONE));
125
126// Given the defaults above, this will use tracing(true), consistencyLevel(ONE)
127mapper.get(uuid, consistencyLevel(ONE));
128```
129
130To reset default options, use the following methods:
131
132```java
133mapper.resetDefaultGetOption();
134mapper.resetDefaultSaveOption();
135mapper.resetDefaultDeleteOption();
136```
137
138#### Access to underlying `Statement`s
139
140Instead of performing an operation directly, it's possible to ask the
141`Mapper` to just return the corresponding `Statement` object. This gives
142the client a chance to customize the statement before executing it.
143
144- `Mapper.saveQuery(entity)`: returns a statement generated by the
145 mapper to save `entity` into the database.
146- `Mapper.getQuery(userId)`: returns a statement to select a row in the
147 database, selected on the given `userId`, and matching the mapped
148 object structure.
149- `Mapper.deleteQuery(userID)`: returns a statement to delete a row in the
150 database given the `userId` provided. This method can also accept a
151 mapped object instance.
152
153#### Manual mapping
154
155`Mapper#map` provides a way to convert the results of a regular query:
156
157```java
158ResultSet results = session.execute("SELECT * FROM user");
159Result<User> users = mapper.map(results);
160for (User u : users) {
161 System.out.println("User : " + u.getUserId());
162}
163```
164
165This method will ignore:
166
167* extra columns in the `ResultSet` that are not mapped for this entity.
168* mapped fields that are not present in the `ResultSet` (setters won't
169 be called so the value will be the one after invocation of the class's
170 default constructor).
171
172[Result] is similar to `ResultSet` but for a given mapped class.
173It provides methods `one()`, `all()`, `iterator()`, `getExecutionInfo()`
174and `isExhausted()`. Note that iterating the `Result` will consume the
175`ResultSet`, and vice-versa.
176
177[Result]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/mapping/Result.html
178
179### Accessors
180
181`Accessor`s provide a way to map custom queries not supported by the
182default entity mappers.
183
184To create an accessor, define a Java interface and annotate each method
185to provide the corresponding CQL query:
186
187```java
188@Accessor
189public interface UserAccessor {
190 @Query("SELECT * FROM user")
191 Result<User> getAll();
192}
193```
194
195The `MappingManager` can then process this interface and automatically generate an
196implementation for it:
197
198```java
199UserAccessor userAccessor = manager.createAccessor(UserAccessor.class);
200User user = userAccessor.getOne(uuid);
201```
202
203Like mappers, accessors are cached at the manager level and thus, are
204thread-safe/sharable.
205
206#### Parameters
207
208A query can have bind markers, that will be set with the method's
209arguments.
210
211With unnamed markers, the order of the arguments must match the order of
212the markers:
213
214```java
215@Query("insert into user (id, name) values (?, ?)")
216ResultSet insert(UUID userId, String name);
217```
218
219With named markers, use [@Param][param] to indicate which parameter
220corresponds to which marker:
221
222```java
223@Query("insert into user (userId, name) values (:u, :n)")
224ResultSet insert(@Param("u") UUID userId, @Param("n") String name);
225```
226
227[param]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/mapping/annotations/Param.html
228
229If a method argument is a Java enumeration, it must be annotated with
230`@Enumerated` to indicate how to convert it to a CQL type (the rules are
231the same as in [mapping definition](../creating/#enumerations)):
232
233```java
234@Query("insert into user (key, gender) values (?,?)")
235ResultSet addUser(int key, @Enumerated(EnumType.ORDINAL) Enum value);
236```
237
238#### Return type
239
240The declared return type of each method affects how the query will get
241executed:
242
243<table border="1" style="text-align:center; width:100%;margin-bottom:1em;">
244 <tr> <td><b>Return type</b></td> <td><b>Effect</b></td> </tr>
245 <tr>
246 <td><code>void</code></td>
247 <td>Synchronous execution, discards the results of the query.</td>
248 </tr>
249 <tr>
250 <td><code>ResultSet</code></td>
251 <td>Synchronous execution, returns unmapped results.</td>
252 </tr>
253 <tr>
254 <td><code>T</code></td>
255 <td><code>T</code> must be a mapped class.<br/>Synchronous execution, returns the first row (or <code>null</code> if there are no results).</td>
256 </tr>
257 <tr>
258 <td><code>Result&lt;T&gt;</code></td>
259 <td><code>T</code> must be a mapped class.<br/>Synchronous execution, returns a list of mapped objects.</td>
260 </tr>
261 <tr>
262 <td><code>ResultSetFuture</code></td>
263 <td>Asynchronous execution, returns unmapped results.</td>
264 </tr>
265 <tr>
266 <td><code>ListenableFuture&lt;T&gt;</code></td>
267 <td><code>T</code> must be a mapped class.<br/>Asynchronous execution, returns the first row (or <code>null</code> if there are no results).</td>
268 </tr>
269 <tr>
270 <td><code>ListenableFuture&lt;Result&lt;T&gt;&gt;</code></td>
271 <td><code>T</code> must be a mapped class.<br/>Asynchronous execution, returns a list of mapped objects.</td>
272 </tr>
273</table>
274
275Example:
276
277```java
278@Query("SELECT * FROM user")
279public ListenableFuture<Result<User>> getAllAsync();
280```
281
282
283#### Customizing the statement
284
285It is possible to customize query parameters to include in a `Accessor`
286query with the annotation [@QueryParameters]. Then, options like
287*consistency level*, *fetchsize* or *tracing* are settable:
288
289```java
290@Query("SELECT * FROM ks.users")
291@QueryParameters(consistency="QUORUM")
292public ListenableFuture<Result<User>> getAllAsync();
293```
294
295[@QueryParameters]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/mapping/annotations/QueryParameters.html