| 1 | ## Using the mapper |
| 2 | |
| 3 | First, create a [MappingManager]. It wraps an existing [Session] |
| 4 | instance: |
| 5 | |
| 6 | ```java |
| 7 | MappingManager manager = new MappingManager(session); |
| 8 | ``` |
| 9 | |
| 10 | `MappingManager` is thread-safe and can be safely shared throughout your |
| 11 | application. You would typically create one instance at startup, right |
| 12 | after your `Session`. |
| 13 | |
| 14 | Note that `MappingManager` will initialize the `Session` if not |
| 15 | previously done (this was not the case in previous driver versions; if |
| 16 | this is a problem for you, see `MappingManager(session, protocolVersion)`). |
| 17 | |
| 18 | ### Entity mappers |
| 19 | |
| 20 | Each entity class (annotated with `@Table`) is managed by a dedicated |
| 21 | [Mapper] object. You obtain this object from the `MappingManager`: |
| 22 | |
| 23 | ```java |
| 24 | Mapper<User> mapper = manager.mapper(User.class); |
| 25 | ``` |
| 26 | |
| 27 | `Mapper` objects are thread-safe. The manager caches them internally, so |
| 28 | calling `manager#mapper` more than once for the same class will return |
| 29 | the 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 | |
| 37 | To save an object, use `Mapper#save`: |
| 38 | |
| 39 | ```java |
| 40 | UUID userId = ...; |
| 41 | User u = new User(userId, "John Doe", new Address("street", 01000)); |
| 42 | mapper.save(u); |
| 43 | ``` |
| 44 | |
| 45 | -------------- |
| 46 | |
| 47 | To retrieve an object, use `Mapper#get`: |
| 48 | |
| 49 | ```java |
| 50 | UUID userId = ...; |
| 51 | User u = mapper.get(userId); |
| 52 | ``` |
| 53 | |
| 54 | `get`'s arguments must match the partition key components (number of |
| 55 | arguments and their types). |
| 56 | |
| 57 | -------------- |
| 58 | |
| 59 | To delete a row in a table, use `Mapper#delete`. This method support |
| 60 | deleting a row given either its primary keys, or the object to delete: |
| 61 | |
| 62 | ```java |
| 63 | UUID userId = ...; |
| 64 | mapper.delete(userId); |
| 65 | mapper.delete(u); |
| 66 | ``` |
| 67 | |
| 68 | -------------- |
| 69 | |
| 70 | All these CRUD operations are synchronous, but the `Mapper` provides |
| 71 | their asynchronous equivalents: |
| 72 | |
| 73 | ```java |
| 74 | ListenableFuture<Void> saveFuture = mapper.saveAsync(u); |
| 75 | ListenableFuture<User> userFuture = mapper.getAsync(userId); |
| 76 | ListenableFuture<Void> deleteFuture = mapper.deleteAsync(userId); |
| 77 | ``` |
| 78 | |
| 79 | #### Mapper options |
| 80 | |
| 81 | The basic CRUD operations accept additional options to customize the |
| 82 | underlying 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 | |
| 94 | To use options, add them to the mapper call after regular parameters: |
| 95 | |
| 96 | ```java |
| 97 | import static com.datastax.driver.mapping.Mapper.Option.*; |
| 98 | |
| 99 | mapper.save(new User(userId, "helloworld"), |
| 100 | timestamp(123456L), tracing(true), ttl(42)); |
| 101 | ``` |
| 102 | |
| 103 | Some 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 | |
| 114 | Note that `Option.consistencyLevel` is redundant with the consistency |
| 115 | level defined by [@Table](../creating/#creating-a-table-entity). |
| 116 | If both are defined, the option will take precedence over the |
| 117 | annotation. |
| 118 | |
| 119 | Default options can be defined for each type of operation: |
| 120 | |
| 121 | ```java |
| 122 | mapper.setDefaultGetOption(tracing(true), consistencyLevel(QUORUM)); |
| 123 | mapper.setDefaultSaveOption(saveNullFields(false)); |
| 124 | mapper.setDefaultDeleteOption(consistencyLevel(ONE)); |
| 125 | |
| 126 | // Given the defaults above, this will use tracing(true), consistencyLevel(ONE) |
| 127 | mapper.get(uuid, consistencyLevel(ONE)); |
| 128 | ``` |
| 129 | |
| 130 | To reset default options, use the following methods: |
| 131 | |
| 132 | ```java |
| 133 | mapper.resetDefaultGetOption(); |
| 134 | mapper.resetDefaultSaveOption(); |
| 135 | mapper.resetDefaultDeleteOption(); |
| 136 | ``` |
| 137 | |
| 138 | #### Access to underlying `Statement`s |
| 139 | |
| 140 | Instead of performing an operation directly, it's possible to ask the |
| 141 | `Mapper` to just return the corresponding `Statement` object. This gives |
| 142 | the 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 |
| 158 | ResultSet results = session.execute("SELECT * FROM user"); |
| 159 | Result<User> users = mapper.map(results); |
| 160 | for (User u : users) { |
| 161 | System.out.println("User : " + u.getUserId()); |
| 162 | } |
| 163 | ``` |
| 164 | |
| 165 | This 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. |
| 173 | It provides methods `one()`, `all()`, `iterator()`, `getExecutionInfo()` |
| 174 | and `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 |
| 182 | default entity mappers. |
| 183 | |
| 184 | To create an accessor, define a Java interface and annotate each method |
| 185 | to provide the corresponding CQL query: |
| 186 | |
| 187 | ```java |
| 188 | @Accessor |
| 189 | public interface UserAccessor { |
| 190 | @Query("SELECT * FROM user") |
| 191 | Result<User> getAll(); |
| 192 | } |
| 193 | ``` |
| 194 | |
| 195 | The `MappingManager` can then process this interface and automatically generate an |
| 196 | implementation for it: |
| 197 | |
| 198 | ```java |
| 199 | UserAccessor userAccessor = manager.createAccessor(UserAccessor.class); |
| 200 | User user = userAccessor.getOne(uuid); |
| 201 | ``` |
| 202 | |
| 203 | Like mappers, accessors are cached at the manager level and thus, are |
| 204 | thread-safe/sharable. |
| 205 | |
| 206 | #### Parameters |
| 207 | |
| 208 | A query can have bind markers, that will be set with the method's |
| 209 | arguments. |
| 210 | |
| 211 | With unnamed markers, the order of the arguments must match the order of |
| 212 | the markers: |
| 213 | |
| 214 | ```java |
| 215 | @Query("insert into user (id, name) values (?, ?)") |
| 216 | ResultSet insert(UUID userId, String name); |
| 217 | ``` |
| 218 | |
| 219 | With named markers, use [@Param][param] to indicate which parameter |
| 220 | corresponds to which marker: |
| 221 | |
| 222 | ```java |
| 223 | @Query("insert into user (userId, name) values (:u, :n)") |
| 224 | ResultSet 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 | |
| 229 | If 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 |
| 231 | the same as in [mapping definition](../creating/#enumerations)): |
| 232 | |
| 233 | ```java |
| 234 | @Query("insert into user (key, gender) values (?,?)") |
| 235 | ResultSet addUser(int key, @Enumerated(EnumType.ORDINAL) Enum value); |
| 236 | ``` |
| 237 | |
| 238 | #### Return type |
| 239 | |
| 240 | The declared return type of each method affects how the query will get |
| 241 | executed: |
| 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<T></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<T></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<Result<T>></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 | |
| 275 | Example: |
| 276 | |
| 277 | ```java |
| 278 | @Query("SELECT * FROM user") |
| 279 | public ListenableFuture<Result<User>> getAllAsync(); |
| 280 | ``` |
| 281 | |
| 282 | |
| 283 | #### Customizing the statement |
| 284 | |
| 285 | It is possible to customize query parameters to include in a `Accessor` |
| 286 | query 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") |
| 292 | public ListenableFuture<Result<User>> getAllAsync(); |
| 293 | ``` |
| 294 | |
| 295 | [@QueryParameters]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/mapping/annotations/QueryParameters.html |