Elffuss BraidHub

kikocis/java-driver public

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