| 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 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. The default constructor |
| 43 | is allowed to be non-public, provided that the security manager, if any, grants |
| 44 | the mapper access to it via [reflection][set-accessible]. |
| 45 | |
| 46 | #### Mapping table columns |
| 47 | |
| 48 | The mapping of each table column can be customized through annotations |
| 49 | placed on either a field declaration, or on a getter method of a |
| 50 | [Java bean property][java-beans]. _Annotations on setters are not |
| 51 | supported and will be silently ignored by the mapper_. |
| 52 | |
| 53 | Users are strongly encouraged to follow the Java bean property |
| 54 | conventions when designing mapped classes: if this is the case, the mapper will |
| 55 | transparently "bind" together fields and accessor methods (getters and setters) |
| 56 | into a single logical abstraction; e.g. a field named `myCol` and a Java |
| 57 | bean property named `myCol` offering a public getter named `getMyCol()` |
| 58 | will be assumed to represent the very same table column, |
| 59 | and annotations for this column are thus allowed to be placed indifferently |
| 60 | on the field declaration, or on the getter method declaration. |
| 61 | |
| 62 | The following mappings are thus equivalent: |
| 63 | |
| 64 | ```java |
| 65 | @Table(name = "users") |
| 66 | public class User { |
| 67 | |
| 68 | // annotation on a field |
| 69 | @PartitionKey |
| 70 | private UUID id; |
| 71 | |
| 72 | public UUID getId() { |
| 73 | return id; |
| 74 | } |
| 75 | |
| 76 | public void setId(UUID id) { |
| 77 | this.id = id; |
| 78 | } |
| 79 | |
| 80 | } |
| 81 | ``` |
| 82 | |
| 83 | ```java |
| 84 | @Table(name = "users") |
| 85 | public class User { |
| 86 | |
| 87 | private UUID id; |
| 88 | |
| 89 | // annotation on a getter method |
| 90 | @PartitionKey |
| 91 | public UUID getId() { |
| 92 | return id; |
| 93 | } |
| 94 | |
| 95 | public void setId(UUID id) { |
| 96 | this.id = id; |
| 97 | } |
| 98 | |
| 99 | } |
| 100 | |
| 101 | ``` |
| 102 | |
| 103 | It is recommended to adopt one strategy or the other for |
| 104 | placing annotations on class members (i.e., either always on fields, or always on getters), |
| 105 | but not both at the same time, unless strictly required. |
| 106 | Annotating fields is usually less verbose, but with polymorphic |
| 107 | data models (see below), annotating getters generally proves to be more flexible. |
| 108 | |
| 109 | If duplicated annotations for a given column are found on the field declaration |
| 110 | and on the getter method declaration, the one declared in the getter method |
| 111 | declaration wins. No warnings are generated in such situations. |
| 112 | |
| 113 | When reading or writing mapped property values, the mapper will first |
| 114 | try to invoke the property getter and setter methods, if they are available; |
| 115 | and if they are not, the mapper will try a direct access to the property's corresponding field. |
| 116 | |
| 117 | A mapped field is thus allowed to be non-public if: |
| 118 | |
| 119 | 1. Reads and writes are done through its public getters and setters; or |
| 120 | 2. The security manager, if any, grants the mapper access to it via [reflection][set-accessible]. |
| 121 | |
| 122 | Note that, according to the [Java Beans specification][java-beans], a setter |
| 123 | must have a `void` return type; the driver, however, will consider as a setter any public method |
| 124 | having a matching signature (i.e., name and parameter types match those expected), |
| 125 | but having a different return type. This allows the usage of "fluent" setters that can |
| 126 | be chained together in a builder-pattern style: |
| 127 | |
| 128 | ```java |
| 129 | @Table(name = "users") |
| 130 | public class User { |
| 131 | |
| 132 | // fluent setters |
| 133 | |
| 134 | public User setId(UUID id) { |
| 135 | this.id = id; |
| 136 | return this; |
| 137 | } |
| 138 | |
| 139 | public User setName(String name) { |
| 140 | this.name = name; |
| 141 | return this; |
| 142 | } |
| 143 | |
| 144 | } |
| 145 | |
| 146 | // chained calls |
| 147 | User user = new User() |
| 148 | .setId(UUIDs.random()) |
| 149 | .setName("John Doe"); |
| 150 | ``` |
| 151 | |
| 152 | [table]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/mapping/annotations/Table.html |
| 153 | [case-sensitive]:http://docs.datastax.com/en/cql/3.3/cql/cql_reference/ucase-lcase_r.html |
| 154 | [consistency level]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/ConsistencyLevel.html |
| 155 | [java-beans]:https://docs.oracle.com/javase/tutorial/javabeans/writing/properties.html |
| 156 | [set-accessible]:https://docs.oracle.com/javase/8/docs/api/java/lang/reflect/AccessibleObject.html#setAccessible-boolean- |
| 157 | |
| 158 | #### Column names |
| 159 | |
| 160 | By default, the mapper tries to map each Java bean property to a |
| 161 | column of the same name. _The mapping is case-insensitive by default_, |
| 162 | i.e., the property `userId` would map to a column named `userid`. |
| 163 | |
| 164 | If you want to use a different name, or [case-sensitive] names, |
| 165 | use the [@Column][column] annotation. |
| 166 | |
| 167 | To specify a different column name, use the `name` attribute: |
| 168 | |
| 169 | ``` |
| 170 | CREATE TABLE users(id uuid PRIMARY KEY, user_name text); |
| 171 | ``` |
| 172 | |
| 173 | ```java |
| 174 | // column name does not match field name |
| 175 | @Column(name = "user_name") |
| 176 | private String userName; |
| 177 | ``` |
| 178 | |
| 179 | When case-sensitive identifiers are required, use the |
| 180 | `caseSensitive` attribute: |
| 181 | |
| 182 | ``` |
| 183 | CREATE TABLE users(id uuid PRIMARY KEY, "userName" text); |
| 184 | ``` |
| 185 | |
| 186 | ```java |
| 187 | // column name is case-sensitive |
| 188 | @Column(caseSensitive = true) |
| 189 | private String userName; |
| 190 | ``` |
| 191 | |
| 192 | [column]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/mapping/annotations/Column.html |
| 193 | |
| 194 | #### Primary key fields |
| 195 | |
| 196 | [@PartitionKey][pk] and [@ClusteringColumn][cc] are used to indicate the |
| 197 | [partition key][pks] and [clustering columns][pks]. In the case of a |
| 198 | composite partition key or multiple clustering columns, the integer |
| 199 | value indicates the position of the column in the key: |
| 200 | |
| 201 | ``` |
| 202 | CREATE TABLE sales(countryCode text, areaCode text, sales int, |
| 203 | PRIMARY KEY((countryCode, areaCode))); |
| 204 | ``` |
| 205 | |
| 206 | ```java |
| 207 | @PartitionKey(0) |
| 208 | private String countryCode; |
| 209 | @PartitionKey(1) |
| 210 | private String areaCode; |
| 211 | ``` |
| 212 | |
| 213 | The order of the indices must match that of the columns in the table |
| 214 | declaration. |
| 215 | |
| 216 | [pk]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/mapping/annotations/PartitionKey.html |
| 217 | [cc]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/mapping/annotations/ClusteringColumn.html |
| 218 | [pks]:http://thelastpickle.com/blog/2013/01/11/primary-keys-in-cql.html |
| 219 | |
| 220 | #### Computed fields |
| 221 | |
| 222 | [@Computed][computed] can be used on properties that are the result of a |
| 223 | computation on the Cassandra side, typically a function call. Native |
| 224 | functions in Cassandra like `writetime()` or [User Defined Functions] are |
| 225 | supported. |
| 226 | |
| 227 | ```java |
| 228 | @Computed("ttl(name)") |
| 229 | Integer ttl; |
| 230 | ``` |
| 231 | |
| 232 | The CQL return type of function must match the type of the property, |
| 233 | otherwise an exception will be thrown. |
| 234 | |
| 235 | Computed fields are ignored when saving an entity. |
| 236 | |
| 237 | `@Computed` does not support case-sensitivity. If the expression |
| 238 | contains case-sensitive column or function names, you'll have to escape |
| 239 | them: |
| 240 | |
| 241 | ```java |
| 242 | @Computed("\"myFunction\"(\"myColumn\")") |
| 243 | int f; |
| 244 | ``` |
| 245 | |
| 246 | Finally, computed properties are only supported with [basic read |
| 247 | operations](../using/#basic-crud-operations) at this time. |
| 248 | Support in [accessors](../using/#accessors) is planned for a future |
| 249 | version (see |
| 250 | [JAVA-832](https://datastax-oss.atlassian.net/browse/JAVA-832)). |
| 251 | |
| 252 | [User Defined Functions]:http://www.planetcassandra.org/blog/user-defined-functions-in-cassandra-3-0/ |
| 253 | [computed]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/mapping/annotations/Computed.html |
| 254 | |
| 255 | #### Transient properties |
| 256 | |
| 257 | By default, the mapper will try to map all fields and Java bean properties |
| 258 | to table columns. [@Transient][transient] can be used to prevent a field or |
| 259 | a Java bean property from being mapped. Like other column-level annotations, |
| 260 | it should be placed on either the field declaration or the property getter method. |
| 261 | |
| 262 | [transient]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/mapping/annotations/Transient.html |
| 263 | |
| 264 | ### Mapping User Types |
| 265 | |
| 266 | [User Defined Types] can also be mapped by using [@UDT][udt]: |
| 267 | |
| 268 | ``` |
| 269 | CREATE TYPE address (street text, zip_code int); |
| 270 | ``` |
| 271 | |
| 272 | ```java |
| 273 | @UDT(keyspace = "ks", name = "address") |
| 274 | class Address { |
| 275 | private String street; |
| 276 | @Field(name = "zip_code") |
| 277 | private int zipCode; |
| 278 | // ... constructors / getters / setters |
| 279 | } |
| 280 | ``` |
| 281 | |
| 282 | `@UDT` takes the following options: |
| 283 | |
| 284 | - `keyspace`: the keyspace for the UDT. |
| 285 | - `name`: the name of the UDT in the database. |
| 286 | - `caseSensitiveKeyspace`: whether the keyspace name is case-sensitive. |
| 287 | - `caseSensitiveType`: whether the UDT name is case-sensitive. |
| 288 | |
| 289 | The class must provide a default constructor. The default constructor |
| 290 | is allowed to be non-public, provided that the security manager, if any, grants |
| 291 | the mapper access to it via [reflection][set-accessible]. |
| 292 | |
| 293 | As for table entities, properties in UDT classes are mapped to an UDT field of the same |
| 294 | name by default. |
| 295 | |
| 296 | To declare a different name or use case-sensitivity, |
| 297 | use the [@Field][field] annotation: |
| 298 | |
| 299 | ```java |
| 300 | @Field(name = "zip_code") |
| 301 | private int zipCode; |
| 302 | ``` |
| 303 | |
| 304 | When a table has a UDT column, the mapper will automatically map it to |
| 305 | the corresponding class: |
| 306 | |
| 307 | ``` |
| 308 | CREATE TABLE company (company_id uuid PRIMARY KEY, name text, address address); |
| 309 | ``` |
| 310 | |
| 311 | ```java |
| 312 | public class Company { |
| 313 | @PartitionKey |
| 314 | @Column(name = "company_id") |
| 315 | private UUID companyId; |
| 316 | private String name; |
| 317 | private Address address; |
| 318 | } |
| 319 | ``` |
| 320 | |
| 321 | This also works with UDTs inside collections or other UDTs, with any arbitrary |
| 322 | nesting level. |
| 323 | |
| 324 | [User Defined Types]: ../../udts/ |
| 325 | [udt]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/mapping/annotations/UDT.html |
| 326 | [field]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/mapping/annotations/Field.html |
| 327 | |
| 328 | ### Mapping collections |
| 329 | |
| 330 | Java collections will be automatically mapped into corresponding |
| 331 | Cassandra types. As in Cassandra, collections can contain all native |
| 332 | types and all [user types](#mapping-user-types) previously defined is |
| 333 | the database. |
| 334 | |
| 335 | Collection and UDT fields should be annotated to indicate whether they are |
| 336 | frozen. Currently this is only for informational purposes (the mapper |
| 337 | won't check that the declarations match the rules in Cassandra). |
| 338 | However it is a good idea to keep using these annotations and make sure |
| 339 | they match the schema, in anticipation for the schema generation features |
| 340 | that will be added in a future version. |
| 341 | The default annotation is [@Frozen][frozen], [@FrozenKey][frozenkey] and |
| 342 | [@FrozenValue][frozenvalue] are also provided for convenience: |
| 343 | |
| 344 | ```java |
| 345 | // Will be mapped as a 'list<text>' |
| 346 | private List<String> stringList; |
| 347 | |
| 348 | // Will be mapped as a 'frozen<list<text>>' |
| 349 | @Frozen |
| 350 | private List<String> frozenStringList; |
| 351 | |
| 352 | // Will be mapped as 'map<frozen<address>, frozen<list<text>>>' |
| 353 | @FrozenKey |
| 354 | @FrozenValue |
| 355 | private Map<Address, List<String>> frozenKeyValueMap; |
| 356 | |
| 357 | // Will be mapped as 'map<text, frozen<list<address>>>' |
| 358 | @FrozenValue |
| 359 | private Map<String, List<Address>> frozenValueMap; |
| 360 | ``` |
| 361 | |
| 362 | [frozen]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/mapping/annotations/Frozen.html |
| 363 | [frozenkey]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/mapping/annotations/FrozenKey.html |
| 364 | [frozenvalue]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/mapping/annotations/FrozenValue.html |
| 365 | |
| 366 | |
| 367 | ### Polymorphism support |
| 368 | |
| 369 | When mapping an entity class or a UDT class, the mapper will transparently |
| 370 | scan superclasses and superinterfaces for annotations on fields and getter methods, |
| 371 | thus enabling the polymorphic mapping of one class hierarchy |
| 372 | into different CQL tables or UDTs. |
| 373 | |
| 374 | Each concrete class must correspond to a table or a UDT, |
| 375 | and should be annotated accordingly with `@Table` or `@UDT`. |
| 376 | This is analogous to the so-called "table per concrete class" |
| 377 | mapping strategy usually found in popular SQL mapping frameworks, such as Hibernate. |
| 378 | |
| 379 | Here is an example of a polymorphic mapping: |
| 380 | |
| 381 | ```sql |
| 382 | CREATE TYPE point2d (x int, y int); |
| 383 | CREATE TYPE point3d (x int, y int, z int); |
| 384 | CREATE TABLE rectangles (id uuid PRIMARY KEY, bottom_left frozen<point2d>, top_right frozen<point2d>); |
| 385 | CREATE TABLE spheres (id uuid PRIMARY KEY, center frozen<point3d>, radius double); |
| 386 | ``` |
| 387 | |
| 388 | ```java |
| 389 | @UDT(name = "point2d") |
| 390 | public class Point2D { |
| 391 | public int x; |
| 392 | public int y; |
| 393 | } |
| 394 | |
| 395 | @UDT(name = "point3d") |
| 396 | public class Point3D extends Point2D { |
| 397 | public int z; |
| 398 | } |
| 399 | |
| 400 | public interface Shape2D { |
| 401 | |
| 402 | @Transient |
| 403 | double getArea(); |
| 404 | |
| 405 | } |
| 406 | |
| 407 | public interface Shape3D { |
| 408 | |
| 409 | @Transient |
| 410 | double getVolume(); |
| 411 | |
| 412 | } |
| 413 | |
| 414 | public abstract class Shape { |
| 415 | |
| 416 | private UUID id; |
| 417 | |
| 418 | @PartitionKey |
| 419 | public UUID getId() { |
| 420 | return id; |
| 421 | } |
| 422 | |
| 423 | public void setId(UUID id) { |
| 424 | this.id = id; |
| 425 | } |
| 426 | |
| 427 | } |
| 428 | |
| 429 | @Table(name = "rectangles") |
| 430 | public class Rectangle extends Shape implements Shape2D { |
| 431 | |
| 432 | private Point2D bottomLeft; |
| 433 | private Point2D topRight; |
| 434 | |
| 435 | @Column(name = "bottom_left") |
| 436 | @Frozen |
| 437 | public Point2D getBottomLeft() { |
| 438 | return bottomLeft; |
| 439 | } |
| 440 | |
| 441 | public void setBottomLeft(Point2D bottomLeft) { |
| 442 | this.bottomLeft = bottomLeft; |
| 443 | } |
| 444 | |
| 445 | @Column(name = "top_right") |
| 446 | @Frozen |
| 447 | public Point2D getTopRight() { |
| 448 | return topRight; |
| 449 | } |
| 450 | |
| 451 | public void setTopRight(Point2D topRight) { |
| 452 | this.topRight = topRight; |
| 453 | } |
| 454 | |
| 455 | @Transient |
| 456 | public double getWidth() { |
| 457 | return Math.abs(topRight.x - bottomLeft.x); |
| 458 | } |
| 459 | |
| 460 | @Transient |
| 461 | public double getHeight() { |
| 462 | return Math.abs(topRight.y - bottomLeft.y); |
| 463 | } |
| 464 | |
| 465 | @Override |
| 466 | public double getArea() { |
| 467 | return getWidth() * getHeight(); |
| 468 | } |
| 469 | |
| 470 | } |
| 471 | |
| 472 | @Table(name = "spheres") |
| 473 | public class Sphere extends Shape implements Shape3D { |
| 474 | |
| 475 | private Point3D center; |
| 476 | private double radius; |
| 477 | |
| 478 | @Frozen |
| 479 | public Point3D getCenter() { |
| 480 | return center; |
| 481 | } |
| 482 | |
| 483 | public void setCenter(Point3D center) { |
| 484 | this.center = center; |
| 485 | } |
| 486 | |
| 487 | public double getRadius() { |
| 488 | return radius; |
| 489 | } |
| 490 | |
| 491 | public void setRadius(double radius) { |
| 492 | this.radius = radius; |
| 493 | } |
| 494 | |
| 495 | @Override |
| 496 | public double getVolume() { |
| 497 | return 4d / 3d * Math.PI * Math.pow(getRadius(), 3); |
| 498 | } |
| 499 | |
| 500 | } |
| 501 | ``` |
| 502 | |
| 503 | One powerful advantage of annotating getter methods is that |
| 504 | annotations are inherited from overridden methods in superclasses and superinterfaces; |
| 505 | in other words, if a getter method is overridden in a subclass, annotations in both |
| 506 | method declarations will get merged together. If duplicated annotations are found during this merge |
| 507 | process, the overriding method's annotations will take precedence over the overridden's. |