| 1 | ## Definition of mapped classes |
| 2 | |
| 3 | The object mapper is configured by annotations on the mapped classes. |
| 4 | |
| 5 | ### Creating a table entity |
| 6 | |
| 7 | A table entity is a class that will be mapped to a table in Cassandra. |
| 8 | It is annotated with [@Table][table]: |
| 9 | |
| 10 | ``` |
| 11 | CREATE TABLE user (user_id uuid PRIMARY KEY, name text); |
| 12 | ``` |
| 13 | |
| 14 | ```java |
| 15 | @Table(keyspace = "ks", name = "users", |
| 16 | readConsistency = "QUORUM", |
| 17 | writeConsistency = "QUORUM", |
| 18 | caseSensitiveKeyspace = false, |
| 19 | caseSensitiveTable = false) |
| 20 | public static class User { |
| 21 | @PartitionKey |
| 22 | @Column(name = "user_id") |
| 23 | private UUID userId; |
| 24 | private String name; |
| 25 | // ... constructors / getters / setters |
| 26 | } |
| 27 | ``` |
| 28 | |
| 29 | `@Table` takes the following options: |
| 30 | |
| 31 | - `keyspace`: the keyspace for the table. |
| 32 | - `name`: the name of the table in the database. |
| 33 | - `caseSensitiveKeyspace`: whether the keyspace name is [case-sensitive]. |
| 34 | - `caseSensitiveTable`: whether the table name is [case-sensitive]. |
| 35 | - `readConsistency`: the [consistency level] that will be used on each |
| 36 | get operation in the mapper. (if unspecified, it defaults to the |
| 37 | cluster-wide setting) |
| 38 | - `writeConsistency`: the [consistency level] that will be used on each |
| 39 | save, or delete operation in the mapper. (if unspecified, it defaults |
| 40 | to the cluster-wide setting) |
| 41 | |
| 42 | The class must provide a default constructor (it can however be private). |
| 43 | |
| 44 | The mapping of each table column can be customized through annotations placed on either a field declaration, |
| 45 | or on a Java bean property getter method. _Annotations on setters are not supported and will be |
| 46 | silently ignored by the mapper_. |
| 47 | |
| 48 | The following mappings are thus equivalent: |
| 49 | |
| 50 | ```java |
| 51 | @Table(name = "users") |
| 52 | public static class User { |
| 53 | |
| 54 | // annotation on a field |
| 55 | @PartitionKey |
| 56 | @Column(name = "user_id") |
| 57 | private UUID userId; |
| 58 | |
| 59 | public UUID getUserId() { |
| 60 | return userId; |
| 61 | } |
| 62 | |
| 63 | public void setUserId(UUID userId) { |
| 64 | this.userId = userId; |
| 65 | } |
| 66 | |
| 67 | } |
| 68 | |
| 69 | @Table(name = "users") |
| 70 | public static class User { |
| 71 | |
| 72 | private UUID userId; |
| 73 | |
| 74 | // annotation on a getter method |
| 75 | @PartitionKey |
| 76 | @Column(name = "user_id") |
| 77 | public UUID getUserId() { |
| 78 | return userId; |
| 79 | } |
| 80 | |
| 81 | public void setUserId(UUID userId) { |
| 82 | this.userId = userId; |
| 83 | } |
| 84 | |
| 85 | } |
| 86 | |
| 87 | ``` |
| 88 | |
| 89 | To explicitly exclude a Java bean property or a field from being mapped, |
| 90 | annotate either the field or the property getter method with `@Transient`. |
| 91 | |
| 92 | The mapper tries to "bind" fields and accessor methods (getters and setters) together |
| 93 | into a single logical abstraction; |
| 94 | it is therefore advised that users follow the [Java bean property conventions] |
| 95 | (java-beans) when designing mapped classes. |
| 96 | |
| 97 | In particular, when reading or writing mapped property values, the mapper will first |
| 98 | try the property getter and setter methods, if they are available; |
| 99 | and if they are not, the mapper will try a direct access to the property's corresponding field. |
| 100 | |
| 101 | [table]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/mapping/annotations/Table.html |
| 102 | [case-sensitive]:http://docs.datastax.com/en/cql/3.3/cql/cql_reference/ucase-lcase_r.html |
| 103 | [consistency level]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/ConsistencyLevel.html |
| 104 | [java-beans]:https://docs.oracle.com/javase/tutorial/javabeans/writing/properties.html |
| 105 | |
| 106 | #### Column names |
| 107 | |
| 108 | By default, the mapper tries to map each Java property to a |
| 109 | case insensitive column of the same name. If you want to use a different |
| 110 | name, or [case-sensitive] names, use the [@Column][column] annotation on |
| 111 | the property. |
| 112 | |
| 113 | [column]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/mapping/annotations/Column.html |
| 114 | |
| 115 | #### Primary key fields |
| 116 | |
| 117 | [@PartitionKey][pk] and [@ClusteringColumn][cc] are used to indicate the |
| 118 | [partition key][pks] and [clustering columns][pks]. In the case of a |
| 119 | composite partition key or multiple clustering columns, the integer |
| 120 | value indicates the position of the column in the key: |
| 121 | |
| 122 | ``` |
| 123 | CREATE TABLE sales(countryCode text, areaCode text, sales int, |
| 124 | PRIMARY KEY((countryCode, areaCode))); |
| 125 | ``` |
| 126 | |
| 127 | ```java |
| 128 | @PartitionKey(0) |
| 129 | private String countryCode; |
| 130 | @PartitionKey(1) |
| 131 | private String areaCode; |
| 132 | ``` |
| 133 | |
| 134 | The order of the indices must match that of the columns in the table |
| 135 | declaration. |
| 136 | |
| 137 | [pk]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/mapping/annotations/PartitionKey.html |
| 138 | [cc]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/mapping/annotations/ClusteringColumn.html |
| 139 | [pks]:http://thelastpickle.com/blog/2013/01/11/primary-keys-in-cql.html |
| 140 | |
| 141 | #### Computed fields |
| 142 | |
| 143 | [@Computed][computed] can be used on properties that are the result of a |
| 144 | computation on the Cassandra side, typically a function call. Native |
| 145 | functions in Cassandra like `writetime()` or [User Defined Functions] are |
| 146 | supported. |
| 147 | |
| 148 | ```java |
| 149 | @Computed("ttl(name)") |
| 150 | Integer ttl; |
| 151 | ``` |
| 152 | |
| 153 | The CQL return type of function must match the type of the property, |
| 154 | otherwise an exception will be thrown. |
| 155 | |
| 156 | Computed fields are ignored when saving an entity. |
| 157 | |
| 158 | `@Computed` does not support case-sensitivity. If the expression |
| 159 | contains case-sensitive column or function names, you'll have to escape |
| 160 | them: |
| 161 | |
| 162 | ```java |
| 163 | @Computed("\"myFunction\"(\"myColumn\")") |
| 164 | int f; |
| 165 | ``` |
| 166 | |
| 167 | Finally, computed properties are only supported with [basic read |
| 168 | operations](../using/#basic-crud-operations) at this time. |
| 169 | Support in [accessors](../using/#accessors) is planned for a future |
| 170 | version (see |
| 171 | [JAVA-832](https://datastax-oss.atlassian.net/browse/JAVA-832)). |
| 172 | |
| 173 | [User Defined Functions]:http://www.planetcassandra.org/blog/user-defined-functions-in-cassandra-3-0/ |
| 174 | [computed]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/mapping/annotations/Computed.html |
| 175 | |
| 176 | #### Transient properties |
| 177 | |
| 178 | [@Transient][transient] can be used to prevent a field or a Java bean property from being mapped. |
| 179 | It should be placed on either the field declaration or the property getter method. |
| 180 | |
| 181 | [transient]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/mapping/annotations/Transient.html |
| 182 | |
| 183 | ### Mapping User Types |
| 184 | |
| 185 | [User Defined Types] can also be mapped by using [@UDT][udt]: |
| 186 | |
| 187 | ``` |
| 188 | CREATE TYPE address (street text, zip_code int); |
| 189 | ``` |
| 190 | |
| 191 | ```java |
| 192 | @UDT(keyspace = "ks", name = "address") |
| 193 | class Address { |
| 194 | private String street; |
| 195 | @Field(name = "zip_code") |
| 196 | private int zipCode; |
| 197 | // ... constructors / getters / setters |
| 198 | } |
| 199 | ``` |
| 200 | |
| 201 | `@UDT` takes the following options: |
| 202 | |
| 203 | - `keyspace`: the keyspace for the UDT. |
| 204 | - `name`: the name of the UDT in the database. |
| 205 | - `caseSensitiveKeyspace`: whether the keyspace name is case-sensitive. |
| 206 | - `caseSensitiveType`: whether the UDT name is case-sensitive. |
| 207 | |
| 208 | The class must provide a default constructor (it can however be private). |
| 209 | |
| 210 | As for table entities, properties in UDT classes are mapped to an UDT field of the same |
| 211 | name by default. |
| 212 | |
| 213 | To declare a different name or use case-sensitivity, |
| 214 | use the [@Field][field] annotation: |
| 215 | |
| 216 | ```java |
| 217 | @Field(name = "zip_code") |
| 218 | private int zipCode; |
| 219 | ``` |
| 220 | |
| 221 | When a table has a UDT column, the mapper will automatically map it to |
| 222 | the corresponding class: |
| 223 | |
| 224 | ``` |
| 225 | CREATE TABLE company (company_id uuid PRIMARY KEY, name text, address address); |
| 226 | ``` |
| 227 | |
| 228 | ```java |
| 229 | public static class Company { |
| 230 | @PartitionKey |
| 231 | @Column(name = "company_id") |
| 232 | private UUID companyId; |
| 233 | private String name; |
| 234 | private Address address; |
| 235 | } |
| 236 | ``` |
| 237 | |
| 238 | This also works with UDTs inside collections or other UDTs, with any arbitrary |
| 239 | nesting level. |
| 240 | |
| 241 | [User Defined Types]: ../../udts/ |
| 242 | [udt]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/mapping/annotations/UDT.html |
| 243 | [field]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/mapping/annotations/Field.html |
| 244 | |
| 245 | ### Mapping collections |
| 246 | |
| 247 | Java collections will be automatically mapped into corresponding |
| 248 | Cassandra types. As in Cassandra, collections can contain all native |
| 249 | types and all [user types](#mapping-user-types) previously defined is |
| 250 | the database. |
| 251 | |
| 252 | Collection and UDT fields should be annotated to indicate whether they are |
| 253 | frozen. Currently this is only for informational purposes (the mapper |
| 254 | won't check that the declarations match the rules in Cassandra). |
| 255 | However it is a good idea to keep using these annotations and make sure |
| 256 | they match the schema, in anticipation for the schema generation features |
| 257 | that will be added in a future version. |
| 258 | The default annotation is [@Frozen][frozen], [@FrozenKey][frozenkey] and |
| 259 | [@FrozenValue][frozenvalue] are also provided for convenience: |
| 260 | |
| 261 | ```java |
| 262 | // Will be mapped as a 'list<text>' |
| 263 | private List<String> stringList; |
| 264 | |
| 265 | // Will be mapped as a 'frozen<list<text>>' |
| 266 | @Frozen |
| 267 | private List<String> frozenStringList; |
| 268 | |
| 269 | // Will be mapped as 'map<frozen<address>, frozen<list<text>>>' |
| 270 | @FrozenKey |
| 271 | @FrozenValue |
| 272 | private Map<Address, List<String>> frozenKeyValueMap; |
| 273 | |
| 274 | // Will be mapped as 'map<text, frozen<list<address>>>' |
| 275 | @FrozenValue |
| 276 | private Map<String, List<Address>> frozenValueMap; |
| 277 | ``` |
| 278 | |
| 279 | [frozen]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/mapping/annotations/Frozen.html |
| 280 | [frozenkey]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/mapping/annotations/FrozenKey.html |
| 281 | [frozenvalue]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/mapping/annotations/FrozenValue.html |
| 282 | |
| 283 | |
| 284 | ### Polymorphism support |
| 285 | |
| 286 | By default, the mapper will consider all Java bean properties and all fields |
| 287 | (including private ones) found in an entity class or in a UDT class, |
| 288 | as well as in their superclasses and superinterfaces. |
| 289 | |
| 290 | This allows for a (basic) polymorphic mapping of a given class hierarchy |
| 291 | into different CQL tables or UDTs. |
| 292 | |
| 293 | Currently, each concrete class must correspond to a table or a UDT, |
| 294 | and should be annotated accordingly. This corresponds to the so called |
| 295 | "Table per concrete class" mapping strategy provided by |
| 296 | some popular SQL mapping frameworks such as Hibernate. |
| 297 | |
| 298 | Here is an example of a polymorphic mapping: |
| 299 | |
| 300 | ```sql |
| 301 | CREATE TYPE point2d (x int, y int); |
| 302 | CREATE TYPE point3d (x int, y int, z int); |
| 303 | CREATE TABLE rectangles (id uuid PRIMARY KEY, bottom_left frozen<point2d>, top_right frozen<point2d>); |
| 304 | CREATE TABLE spheres (id uuid PRIMARY KEY, center frozen<point3d>, radius double); |
| 305 | ``` |
| 306 | |
| 307 | ```java |
| 308 | @UDT(name = "point2d") |
| 309 | public class Point2D { |
| 310 | public int x; |
| 311 | public int y; |
| 312 | } |
| 313 | |
| 314 | @UDT(name = "point3d") |
| 315 | public class Point3D extends Point2D { |
| 316 | public int z; |
| 317 | } |
| 318 | |
| 319 | public interface Shape2D { |
| 320 | |
| 321 | @Transient |
| 322 | double getArea(); |
| 323 | |
| 324 | } |
| 325 | |
| 326 | public interface Shape3D { |
| 327 | |
| 328 | @Transient |
| 329 | double getVolume(); |
| 330 | |
| 331 | } |
| 332 | |
| 333 | public abstract class Shape { |
| 334 | |
| 335 | private UUID id; |
| 336 | |
| 337 | @PartitionKey |
| 338 | public UUID getId() { |
| 339 | return id; |
| 340 | } |
| 341 | |
| 342 | public void setId(UUID id) { |
| 343 | this.id = id; |
| 344 | } |
| 345 | |
| 346 | } |
| 347 | |
| 348 | @Table(name = "rectangles") |
| 349 | public class Rectangle extends Shape implements Shape2D { |
| 350 | |
| 351 | private Point2D bottomLeft; |
| 352 | private Point2D topRight; |
| 353 | |
| 354 | @Column(name = "bottom_left") |
| 355 | @Frozen |
| 356 | public Point2D getBottomLeft() { |
| 357 | return bottomLeft; |
| 358 | } |
| 359 | |
| 360 | public void setBottomLeft(Point2D bottomLeft) { |
| 361 | this.bottomLeft = bottomLeft; |
| 362 | } |
| 363 | |
| 364 | @Column(name = "top_right") |
| 365 | @Frozen |
| 366 | public Point2D getTopRight() { |
| 367 | return topRight; |
| 368 | } |
| 369 | |
| 370 | public void setTopRight(Point2D topRight) { |
| 371 | this.topRight = topRight; |
| 372 | } |
| 373 | |
| 374 | @Transient |
| 375 | public double getWidth() { |
| 376 | return Math.abs(topRight.x - bottomLeft.x); |
| 377 | } |
| 378 | |
| 379 | @Transient |
| 380 | public double getHeight() { |
| 381 | return Math.abs(topRight.y - bottomLeft.y); |
| 382 | } |
| 383 | |
| 384 | @Override |
| 385 | public double getArea() { |
| 386 | return getWidth() * getHeight(); |
| 387 | } |
| 388 | |
| 389 | } |
| 390 | |
| 391 | @Table(name = "spheres") |
| 392 | public class Sphere extends Shape implements Shape3D { |
| 393 | |
| 394 | private Point3D center; |
| 395 | private double radius; |
| 396 | |
| 397 | @Frozen |
| 398 | public Point3D getCenter() { |
| 399 | return center; |
| 400 | } |
| 401 | |
| 402 | public void setCenter(Point3D center) { |
| 403 | this.center = center; |
| 404 | } |
| 405 | |
| 406 | public double getRadius() { |
| 407 | return radius; |
| 408 | } |
| 409 | |
| 410 | public void setRadius(double radius) { |
| 411 | this.radius = radius; |
| 412 | } |
| 413 | |
| 414 | @Override |
| 415 | public double getVolume() { |
| 416 | return 4d / 3d * Math.PI * Math.pow(getRadius(), 3); |
| 417 | } |
| 418 | |
| 419 | } |
| 420 | ``` |
| 421 | |
| 422 | It is usually recommended to adopt one strategy or the other for |
| 423 | placing annotations on class members (i.e., either always on fields, or always on getters), |
| 424 | but not both at the same time, unless strictly required. |
| 425 | Usually, annotating getters is more flexible than annotating fields. |
| 426 | |
| 427 | If the mapper needs to disambiguate a specific property mapping, |
| 428 | note that annotations on getters will always take precedence over annotations on fields. |
| 429 | Likewise, if a getter method is overridden in a subclass, annotations in both |
| 430 | methods will get merged together, and in case of conflict, the overriding method's annotations |
| 431 | will take precedence over the overridden's. |
| 432 | |