Elffuss BraidHub

kikocis/java-driver public

dd6f2ca5f35e · 12.4 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 (it can however be private).
43
44The mapping of each table column can be customized through annotations placed on either a field declaration,
45or on a Java bean property getter method. _Annotations on setters are not supported and will be
46silently ignored by the mapper_.
47
48The following mappings are thus equivalent:
49
50```java
51@Table(name = "users")
52public 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")
70public 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
89To explicitly exclude a Java bean property or a field from being mapped,
90annotate either the field or the property getter method with `@Transient`.
91
92The mapper tries to "bind" fields and accessor methods (getters and setters) together
93into a single logical abstraction;
94it is therefore advised that users follow the [Java bean property conventions]
95(java-beans) when designing mapped classes.
96
97In particular, when reading or writing mapped property values, the mapper will first
98try the property getter and setter methods, if they are available;
99and 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
108By default, the mapper tries to map each Java property to a
109case insensitive column of the same name. If you want to use a different
110name, or [case-sensitive] names, use the [@Column][column] annotation on
111the 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
119composite partition key or multiple clustering columns, the integer
120value indicates the position of the column in the key:
121
122```
123CREATE TABLE sales(countryCode text, areaCode text, sales int,
124 PRIMARY KEY((countryCode, areaCode)));
125```
126
127```java
128@PartitionKey(0)
129private String countryCode;
130@PartitionKey(1)
131private String areaCode;
132```
133
134The order of the indices must match that of the columns in the table
135declaration.
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
144computation on the Cassandra side, typically a function call. Native
145functions in Cassandra like `writetime()` or [User Defined Functions] are
146supported.
147
148```java
149@Computed("ttl(name)")
150Integer ttl;
151```
152
153The CQL return type of function must match the type of the property,
154otherwise an exception will be thrown.
155
156Computed fields are ignored when saving an entity.
157
158`@Computed` does not support case-sensitivity. If the expression
159contains case-sensitive column or function names, you'll have to escape
160them:
161
162```java
163@Computed("\"myFunction\"(\"myColumn\")")
164int f;
165```
166
167Finally, computed properties are only supported with [basic read
168operations](../using/#basic-crud-operations) at this time.
169Support in [accessors](../using/#accessors) is planned for a future
170version (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.
179It 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```
188CREATE TYPE address (street text, zip_code int);
189```
190
191```java
192@UDT(keyspace = "ks", name = "address")
193class 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
208The class must provide a default constructor (it can however be private).
209
210As for table entities, properties in UDT classes are mapped to an UDT field of the same
211name by default.
212
213To declare a different name or use case-sensitivity,
214use the [@Field][field] annotation:
215
216```java
217@Field(name = "zip_code")
218private int zipCode;
219```
220
221When a table has a UDT column, the mapper will automatically map it to
222the corresponding class:
223
224```
225CREATE TABLE company (company_id uuid PRIMARY KEY, name text, address address);
226```
227
228```java
229public 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
238This also works with UDTs inside collections or other UDTs, with any arbitrary
239nesting 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
247Java collections will be automatically mapped into corresponding
248Cassandra types. As in Cassandra, collections can contain all native
249types and all [user types](#mapping-user-types) previously defined is
250the database.
251
252Collection and UDT fields should be annotated to indicate whether they are
253frozen. Currently this is only for informational purposes (the mapper
254won't check that the declarations match the rules in Cassandra).
255However it is a good idea to keep using these annotations and make sure
256they match the schema, in anticipation for the schema generation features
257that will be added in a future version.
258The 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>'
263private List<String> stringList;
264
265// Will be mapped as a 'frozen<list<text>>'
266@Frozen
267private List<String> frozenStringList;
268
269// Will be mapped as 'map<frozen<address>, frozen<list<text>>>'
270@FrozenKey
271@FrozenValue
272private Map<Address, List<String>> frozenKeyValueMap;
273
274// Will be mapped as 'map<text, frozen<list<address>>>'
275@FrozenValue
276private 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
286By 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,
288as well as in their superclasses and superinterfaces.
289
290This allows for a (basic) polymorphic mapping of a given class hierarchy
291into different CQL tables or UDTs.
292
293Currently, each concrete class must correspond to a table or a UDT,
294and should be annotated accordingly. This corresponds to the so called
295"Table per concrete class" mapping strategy provided by
296some popular SQL mapping frameworks such as Hibernate.
297
298Here is an example of a polymorphic mapping:
299
300```sql
301CREATE TYPE point2d (x int, y int);
302CREATE TYPE point3d (x int, y int, z int);
303CREATE TABLE rectangles (id uuid PRIMARY KEY, bottom_left frozen<point2d>, top_right frozen<point2d>);
304CREATE TABLE spheres (id uuid PRIMARY KEY, center frozen<point3d>, radius double);
305```
306
307```java
308@UDT(name = "point2d")
309public class Point2D {
310 public int x;
311 public int y;
312}
313
314@UDT(name = "point3d")
315public class Point3D extends Point2D {
316 public int z;
317}
318
319public interface Shape2D {
320
321 @Transient
322 double getArea();
323
324}
325
326public interface Shape3D {
327
328 @Transient
329 double getVolume();
330
331}
332
333public 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")
349public 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")
392public 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
422It is usually recommended to adopt one strategy or the other for
423placing annotations on class members (i.e., either always on fields, or always on getters),
424but not both at the same time, unless strictly required.
425Usually, annotating getters is more flexible than annotating fields.
426
427If the mapper needs to disambiguate a specific property mapping,
428note that annotations on getters will always take precedence over annotations on fields.
429Likewise, if a getter method is overridden in a subclass, annotations in both
430methods will get merged together, and in case of conflict, the overriding method's annotations
431will take precedence over the overridden's.
432