Elffuss BraidHub

kikocis/java-driver public

057dd8d141d6 · 10.3 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/2.1/com/datastax/driver/mapping/Mapper.html
32[MappingManager]:http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/mapping/MappingManager.html
33[Session]:http://docs.datastax.com/en/drivers/java/2.1/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).
92
93To use options, add them to the mapper call after regular parameters:
94
95```java
96import static com.datastax.driver.mapping.Mapper.Option.*;
97
98mapper.save(new User(userId, "helloworld"),
99 timestamp(123456L), tracing(true), ttl(42));
100```
101
102Some options don't apply to all operations:
103
104<table border="1" style="text-align:center; width:100%;margin-bottom:1em;">
105 <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>
106 <tr> <td>Ttl</td> <td>yes</td> <td>no</td> <td>no</td> </tr>
107 <tr> <td>Timestamp</td> <td>yes</td> <td>no</td> <td>yes</td> </tr>
108 <tr> <td>ConsistencyLevel</td> <td>yes</td> <td>yes</td> <td>yes</td> </tr>
109 <tr> <td>Tracing</td> <td>yes</td> <td>yes</td> <td>yes</td> </tr>
110 <tr> <td>SaveNullFields</td> <td>yes</td> <td>no</td> <td>no</td> </tr>
111</table>
112
113Note that `Option.consistencyLevel` is redundant with the consistency
114level defined by [@Table](../creating/#creating-a-table-entity).
115If both are defined, the option will take precedence over the
116annotation.
117
118Default options can be defined for each type of operation:
119
120```java
121mapper.setDefaultGetOption(tracing(true), consistencyLevel(QUORUM));
122mapper.setDefaultSaveOption(saveNullFields(false));
123mapper.setDefaultDeleteOption(consistencyLevel(ONE));
124
125// Given the defaults above, this will use tracing(true), consistencyLevel(ONE)
126mapper.get(uuid, consistencyLevel(ONE));
127```
128
129To reset default options, use the following methods:
130
131```java
132mapper.resetDefaultGetOption();
133mapper.resetDefaultSaveOption();
134mapper.resetDefaultDeleteOption();
135```
136
137#### Access to underlying `Statement`s
138
139Instead of performing an operation directly, it's possible to ask the
140`Mapper` to just return the corresponding `Statement` object. This gives
141the client a chance to customize the statement before executing it.
142
143- `Mapper.saveQuery(entity)`: returns a statement generated by the
144 mapper to save `entity` into the database.
145- `Mapper.getQuery(userId)`: returns a statement to select a row in the
146 database, selected on the given `userId`, and matching the mapped
147 object structure.
148- `Mapper.deleteQuery(userID)`: returns a statement delete a row in the
149 database given the `userId` provided. This method can also accept a
150 mapped object instance.
151
152#### Manual mapping
153
154`Mapper#map` provides a way to converts the results of a regular query:
155
156```java
157ResultSet results = session.execute("SELECT * FROM user");
158Result<User> users = mapper.map(results);
159for (User u : users) {
160 System.out.println("User : " + u.getUserId());
161}
162```
163
164This method will ignore:
165
166* extra columns in the `ResultSet` that are not mapped for this entity.
167* mapped fields that are not present in the `ResultSet` (setters won't
168 be called so the value will be the one after invocation of the class's
169 default constructor).
170
171[Result] is similar to `ResultSet` but for a given mapped class.
172It provides methods `one()`, `all()`, `iterator()`, `getExecutionInfo()`
173and `isExhausted()`. Note that iterating the `Result` will consume the
174`ResultSet`, and vice-versa.
175
176[Result]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/mapping/Result.html
177
178### UDT Mappers
179
180A UDT will be automatically mapped when it is part of a table-level
181class (as shown [here](../creating/#mapping-user-types)).
182
183However, there might be cases where it is useful to convert a mapped
184instance to the corresponding [UDTValue][UDTValue] (and back). The
185mapper provides an [UDTMapper] for that purpose:
186
187```java
188UDTMapper<Address> addressMapper = manager.getUDTMapper(Address.class);
189Address address = addressMapper.fromUDT(udtValue);
190UDTValue value = addressMapper.toUDT(address);
191```
192
193[UDTValue]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/UDTValue.html
194[UDTMapper]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/mapping/UDTMapper.html
195
196### Accessors
197
198`Accessor`s provide a way to map custom queries not supported by the
199default entity mappers.
200
201To create an accessor, define a Java interface and annotate each method
202to provide the corresponding CQL query:
203
204```java
205@Accessor
206public interface UserAccessor {
207 @Query("SELECT * FROM user")
208 Result<User> getAll();
209}
210```
211
212The `MappingManager` can then process this class and generate an
213implementation:
214
215```java
216UserAccessor userAccessor = manager.createAccessor(UserAccessor.class);
217User user = userAccessor.getOne(uuid);
218```
219
220Like mappers, accessors are cached at the manager level and thus, are
221thread-safe/sharable.
222
223#### Parameters
224
225A query can have bind markers, that will be set with the method's
226arguments.
227
228With unnamed markers, the order of the arguments must match the order of
229the markers:
230
231```java
232@Query("insert into user (id, name) values (?, ?)")
233ResultSet insert(UUID userId, String name);
234```
235
236With named markers, use [@Param][param] to indicate which parameter
237corresponds to which marker:
238
239```java
240@Query("insert into user (userId, name) values (:u, :n)")
241ResultSet insert(@Param("u") UUID userId, @Param("n") String name);
242```
243
244[param]:http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/mapping/annotations/Param.html
245
246If a method argument is a Java enumeration, it must be annotated with
247`@Enumerated` to indicate how to convert it to a CQL type (the rules are
248the same as in [mapping definition](http://localhost:9090/features/object_mapper/creating/#enumerations)):
249
250```java
251@Query("insert into user (key, gender) values (?,?)")
252ResultSet addUser(int key, @Enumerated(EnumType.ORDINAL) Enum value);
253```
254
255#### Return type
256
257The declared return type of each method affects how the query will get
258executed:
259
260<table border="1" style="text-align:center; width:100%;margin-bottom:1em;">
261 <tr> <td><b>Return type</b></td> <td><b>Effect</b></td> </tr>
262 <tr>
263 <td><code>void</code></td>
264 <td>Synchronous execution, discards the results of the query.</td>
265 </tr>
266 <tr>
267 <td><code>ResultSet</code></td>
268 <td>Synchronous execution, returns unmapped results.</td>
269 </tr>
270 <tr>
271 <td><code>T</code></td>
272 <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>
273 </tr>
274 <tr>
275 <td><code>Result&lt;T&gt;</code></td>
276 <td><code>T</code> must be a mapped class.<br/>Synchronous execution, returns a list of mapped objects.</td>
277 </tr>
278 <tr>
279 <td><code>ResultSetFuture</code></td>
280 <td>Asynchronous execution, returns unmapped results.</td>
281 </tr>
282 <tr>
283 <td><code>ListenableFuture&lt;T&gt;</code></td>
284 <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>
285 </tr>
286 <tr>
287 <td><code>ListenableFuture&lt;Result&lt;T&gt;&gt;</code></td>
288 <td><code>T</code> must be a mapped class.<br/>Asynchronous execution, returns a list of mapped objects.</td>
289 </tr>
290</table>
291
292Example:
293
294```java
295@Query("SELECT * FROM user")
296public ListenableFuture<Result<User>> getAllAsync();
297```
298
299
300#### Customizing the statement
301
302It is possible to customize query parameters to include in a `Accessor`
303query with the annotation [@QueryParameters]. Then, options like
304*consistency level*, *fetchsize* or *tracing* are settable:
305
306```java
307@Query("SELECT * FROM ks.users")
308@QueryParameters(consistency="QUORUM")
309public ListenableFuture<Result<User>> getAllAsync();
310```
311
312[@QueryParameters]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/mapping/annotations/QueryParameters.html