Elffuss BraidHub

kikocis/java-driver public

e0b1e4942e30 · 14.8 KiBRenderedRawPermalink
1## Definition of mapped classes
2
3The object mapper is configured by annotations on the mapped classes.
4
5### Creating a table entity
6
7A table entity is a class that will be mapped to a table in Cassandra.
8It is annotated with [@Table][table]:
9
10```
11CREATE 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)
20public 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
42The class must provide a default constructor. The default constructor
43is allowed to be non-public, provided that the security manager, if any, grants
44the mapper access to it via [reflection][set-accessible].
45
46#### Mapping table columns
47
48The mapping of each table column can be customized through annotations
49placed on either a field declaration, or on a getter method of a
50[Java bean property][java-beans]. _Annotations on setters are not
51supported and will be silently ignored by the mapper_.
52
53Users are strongly encouraged to follow the Java bean property
54conventions when designing mapped classes: if this is the case, the mapper will
55transparently "bind" together fields and accessor methods (getters and setters)
56into a single logical abstraction; e.g. a field named `myCol` and a Java
57bean property named `myCol` offering a public getter named `getMyCol()`
58will be assumed to represent the very same table column,
59and annotations for this column are thus allowed to be placed indifferently
60on the field declaration, or on the getter method declaration.
61
62The following mappings are thus equivalent:
63
64```java
65@Table(name = "users")
66public 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")
85public 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
103It is recommended to adopt one strategy or the other for
104placing annotations on class members (i.e., either always on fields, or always on getters),
105but not both at the same time, unless strictly required.
106Annotating fields is usually less verbose, but with polymorphic
107data models (see below), annotating getters generally proves to be more flexible.
108
109If duplicated annotations for a given column are found on the field declaration
110and on the getter method declaration, the one declared in the getter method
111declaration wins. No warnings are generated in such situations.
112
113When reading or writing mapped property values, the mapper will first
114try to invoke the property getter and setter methods, if they are available;
115and if they are not, the mapper will try a direct access to the property's corresponding field.
116
117A mapped field is thus allowed to be non-public if:
118
1191. Reads and writes are done through its public getters and setters; or
1202. The security manager, if any, grants the mapper access to it via [reflection][set-accessible].
121
122Note that, according to the [Java Beans specification][java-beans], a setter
123must have a `void` return type; the driver, however, will consider as a setter any public method
124having a matching signature (i.e., name and parameter types match those expected),
125but having a different return type. This allows the usage of "fluent" setters that can
126be chained together in a builder-pattern style:
127
128```java
129@Table(name = "users")
130public 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
147User 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
160By default, the mapper tries to map each Java bean property to a
161column of the same name. _The mapping is case-insensitive by default_,
162i.e., the property `userId` would map to a column named `userid`.
163
164If you want to use a different name, or [case-sensitive] names,
165use the [@Column][column] annotation.
166
167To specify a different column name, use the `name` attribute:
168
169```
170CREATE 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")
176private String userName;
177```
178
179When case-sensitive identifiers are required, use the
180`caseSensitive` attribute:
181
182```
183CREATE TABLE users(id uuid PRIMARY KEY, "userName" text);
184```
185
186```java
187// column name is case-sensitive
188@Column(caseSensitive = true)
189private 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
198composite partition key or multiple clustering columns, the integer
199value indicates the position of the column in the key:
200
201```
202CREATE TABLE sales(countryCode text, areaCode text, sales int,
203 PRIMARY KEY((countryCode, areaCode)));
204```
205
206```java
207@PartitionKey(0)
208private String countryCode;
209@PartitionKey(1)
210private String areaCode;
211```
212
213The order of the indices must match that of the columns in the table
214declaration.
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
223computation on the Cassandra side, typically a function call. Native
224functions in Cassandra like `writetime()` or [User Defined Functions] are
225supported.
226
227```java
228@Computed("ttl(name)")
229Integer ttl;
230```
231
232The CQL return type of function must match the type of the property,
233otherwise an exception will be thrown.
234
235Computed fields are ignored when saving an entity.
236
237`@Computed` does not support case-sensitivity. If the expression
238contains case-sensitive column or function names, you'll have to escape
239them:
240
241```java
242@Computed("\"myFunction\"(\"myColumn\")")
243int f;
244```
245
246Finally, computed properties are only supported with [basic read
247operations](../using/#basic-crud-operations) at this time.
248Support in [accessors](../using/#accessors) is planned for a future
249version (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
257By default, the mapper will try to map all fields and Java bean properties
258to table columns. [@Transient][transient] can be used to prevent a field or
259a Java bean property from being mapped. Like other column-level annotations,
260it 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```
269CREATE TYPE address (street text, zip_code int);
270```
271
272```java
273@UDT(keyspace = "ks", name = "address")
274class 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
289The class must provide a default constructor. The default constructor
290is allowed to be non-public, provided that the security manager, if any, grants
291the mapper access to it via [reflection][set-accessible].
292
293As for table entities, properties in UDT classes are mapped to an UDT field of the same
294name by default.
295
296To declare a different name or use case-sensitivity,
297use the [@Field][field] annotation:
298
299```java
300@Field(name = "zip_code")
301private int zipCode;
302```
303
304When a table has a UDT column, the mapper will automatically map it to
305the corresponding class:
306
307```
308CREATE TABLE company (company_id uuid PRIMARY KEY, name text, address address);
309```
310
311```java
312public class Company {
313 @PartitionKey
314 @Column(name = "company_id")
315 private UUID companyId;
316 private String name;
317 private Address address;
318}
319```
320
321This also works with UDTs inside collections or other UDTs, with any arbitrary
322nesting 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
330Java collections will be automatically mapped into corresponding
331Cassandra types. As in Cassandra, collections can contain all native
332types and all [user types](#mapping-user-types) previously defined is
333the database.
334
335Collection and UDT fields should be annotated to indicate whether they are
336frozen. Currently this is only for informational purposes (the mapper
337won't check that the declarations match the rules in Cassandra).
338However it is a good idea to keep using these annotations and make sure
339they match the schema, in anticipation for the schema generation features
340that will be added in a future version.
341The 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>'
346private List<String> stringList;
347
348// Will be mapped as a 'frozen<list<text>>'
349@Frozen
350private List<String> frozenStringList;
351
352// Will be mapped as 'map<frozen<address>, frozen<list<text>>>'
353@FrozenKey
354@FrozenValue
355private Map<Address, List<String>> frozenKeyValueMap;
356
357// Will be mapped as 'map<text, frozen<list<address>>>'
358@FrozenValue
359private 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
369When mapping an entity class or a UDT class, the mapper will transparently
370scan superclasses and superinterfaces for annotations on fields and getter methods,
371thus enabling the polymorphic mapping of one class hierarchy
372into different CQL tables or UDTs.
373
374Each concrete class must correspond to a table or a UDT,
375and should be annotated accordingly with `@Table` or `@UDT`.
376This is analogous to the so-called "table per concrete class"
377mapping strategy usually found in popular SQL mapping frameworks, such as Hibernate.
378
379Here is an example of a polymorphic mapping:
380
381```sql
382CREATE TYPE point2d (x int, y int);
383CREATE TYPE point3d (x int, y int, z int);
384CREATE TABLE rectangles (id uuid PRIMARY KEY, bottom_left frozen<point2d>, top_right frozen<point2d>);
385CREATE TABLE spheres (id uuid PRIMARY KEY, center frozen<point3d>, radius double);
386```
387
388```java
389@UDT(name = "point2d")
390public class Point2D {
391 public int x;
392 public int y;
393}
394
395@UDT(name = "point3d")
396public class Point3D extends Point2D {
397 public int z;
398}
399
400public interface Shape2D {
401
402 @Transient
403 double getArea();
404
405}
406
407public interface Shape3D {
408
409 @Transient
410 double getVolume();
411
412}
413
414public 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")
430public 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")
473public 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
503One powerful advantage of annotating getter methods is that
504annotations are inherited from overridden methods in superclasses and superinterfaces;
505in other words, if a getter method is overridden in a subclass, annotations in both
506method declarations will get merged together. If duplicated annotations are found during this merge
507process, the overriding method's annotations will take precedence over the overridden's.