Elffuss BraidHub

kikocis/java-driver public

3.1.x · 16.0 KiBRenderedRawPermalink
1## Optional codecs
2
3The driver's "extras" module provides additional [codec](../) implementations: these codecs are not required by core
4driver features, but will probably prove useful in a lot of client applications. You can also study their source code as
5a reference to write your own.
6
7The module is published as a separate Maven artifact:
8
9```xml
10<dependency>
11 <groupId>com.datastax.cassandra</groupId>
12 <artifactId>cassandra-driver-extras</artifactId>
13 <version>3.1.4</version>
14</dependency>
15```
16
17It also declares a number of optional dependencies, that you'll need to explicitly re-declare in your application
18depending on which codecs you plan to use (this will be covered for each case below).
19
20### Temporal types
21
22JDK 8 and Joda Time support have often been requested; they're not in the core module because we want to preserve
23compatibility with older JDKs and avoid extra dependencies.
24
25#### JDK 8
26
27[InstantCodec] maps [Instant] to CQL's `timestamp`:
28
29```java
30import com.datastax.driver.extras.codecs.jdk8.InstantCodec;
31import java.time.Instant;
32
33cluster.getConfiguration().getCodecRegistry()
34 .register(InstantCodec.instance);
35
36// schema: CREATE TABLE example(id int PRIMARY KEY, t timestamp)
37session.execute("INSERT INTO example (id, t) VALUES (1, ?)",
38 Instant.parse("2010-06-30T01:20:30Z"));
39```
40
41Similarly:
42
43* [LocalDateCodec] maps [LocalDate] to `date`;
44* [LocalTimeCodec] maps [LocalTime] to `time`.
45
46One problem with `timestamp` is that it does not store time zones. [ZonedDateTimeCodec] addresses that, by mapping a
47[ZonedDateTime] to a `tuple<timestamp,varchar>`:
48
49```java
50// Due to internal implementation details, you have to retrieve the tuple type from a live cluster:
51TupleType tupleType = cluster.getMetadata()
52 .newTupleType(DataType.timestamp(), DataType.varchar());
53cluster.getConfiguration().getCodecRegistry()
54 .register(new ZonedDateTimeCodec(tupleType));
55
56// schema: CREATE TABLE example(id int PRIMARY KEY, t tuple<timestamp,varchar>)
57session.execute("INSERT INTO example (id, t) VALUES (1, ?)",
58 ZonedDateTime.parse("2010-06-30T01:20:47.999+01:00"));
59```
60
61[InstantCodec]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/extras/codecs/jdk8/InstantCodec.html
62[LocalDateCodec]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/extras/codecs/jdk8/LocalDateCodec.html
63[LocalTimeCodec]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/extras/codecs/jdk8/LocalTimeCodec.html
64[ZonedDateTimeCodec]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/extras/codecs/jdk8/ZonedDateTimeCodec.html
65[Instant]: https://docs.oracle.com/javase/8/docs/api/java/time/Instant.html
66[LocalDate]: https://docs.oracle.com/javase/8/docs/api/java/time/LocalDate.html
67[LocalTime]: https://docs.oracle.com/javase/8/docs/api/java/time/LocalTime.html
68[ZonedDateTime]: https://docs.oracle.com/javase/8/docs/api/java/time/ZonedDateTime.html
69
70
71#### Joda time
72
73These codecs require an explicit dependency on Joda Time in your application:
74
75```xml
76<dependency>
77 <groupId>joda-time</groupId>
78 <artifactId>joda-time</artifactId>
79 <version>2.9.1</version>
80</dependency>
81```
82
83Like for JDK8, there is a codec for each time type:
84
85* [InstantCodec][InstantCodec_joda]: maps [Instant][Instant_joda] to `timestamp`;
86* [LocalDateCodec][LocalDateCodec_joda]: maps [LocalDate][LocalDate_joda] to `date`;
87* [LocalTimeCodec][LocalTimeCodec_joda]: maps [LocalTime][LocalTime_joda] to `time`.
88
89```java
90import com.datastax.driver.extras.codecs.joda.InstantCodec;
91import org.joda.time.Instant;
92
93cluster.getConfiguration().getCodecRegistry()
94 .register(InstantCodec.instance);
95
96// schema: CREATE TABLE example(id int PRIMARY KEY, t timestamp)
97session.execute("INSERT INTO example (id, t) VALUES (1, ?)",
98 Instant.parse("2010-06-30T01:20:30Z"));
99```
100
101And [DateTimeCodec] can save [DateTime] instances with a time zone:
102
103```java
104TupleType tupleType = cluster.getMetadata()
105 .newTupleType(DataType.timestamp(), DataType.varchar());
106cluster.getConfiguration().getCodecRegistry()
107 .register(new DateTimeCodec(tupleType));
108
109// schema: CREATE TABLE example(id int PRIMARY KEY, t tuple<timestamp,varchar>)
110session.execute("INSERT INTO example (id, t) VALUES (1, ?)",
111 DateTime.parse("2010-06-30T01:20:47.999+01:00"));
112```
113
114[InstantCodec_joda]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/extras/codecs/joda/InstantCodec.html
115[LocalDateCodec_joda]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/extras/codecs/joda/LocalDateCodec.html
116[LocalTimeCodec_joda]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/extras/codecs/joda/LocalTimeCodec.html
117[DateTimeCodec]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/extras/codecs/joda/DateTimeCodec.html
118[DateTime]: http://www.joda.org/joda-time/apidocs/org/joda/time/DateTime.html
119[Instant_joda]: http://www.joda.org/joda-time/apidocs/org/joda/time/Instant.html
120[LocalDate_joda]: http://www.joda.org/joda-time/apidocs/org/joda/time/LocalDate.html
121[LocalTime_joda]: http://www.joda.org/joda-time/apidocs/org/joda/time/LocalTime.html
122
123
124#### Primitive types
125
126Time can also be expressed as simple durations:
127
128* [SimpleTimestampCodec] maps `timestamp` to a primitive Java `long` representing the number of milliseconds since the
129 Epoch;
130* [SimpleDateCodec] maps `date` to a primitive Java `int` representing the number of days since the Epoch.
131
132There is no extra codec for `time`, because by default the driver already maps that type to a `long` representing the
133number of milliseconds since midnight.
134
135[SimpleTimestampCodec]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/extras/codecs/date/SimpleTimestampCodec.html
136[SimpleDateCodec]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/extras/codecs/date/SimpleDateCodec.html
137
138
139### Enums
140
141Enums can be mapped in two different ways:
142
143[EnumNameCodec] stores enum constants as a `varchar` representing their [name]:
144
145```java
146enum State {INIT, RUNNING, STOPPING, STOPPED}
147
148cluster.getConfiguration().getCodecRegistry()
149 .register(new EnumNameCodec<State>(State.class));
150
151// schema: create table name_example(id int PRIMARY KEY, state text)
152session.execute("insert into name_example (id, state) values (1, ?)", State.INIT);
153// state is saved as 'INIT'
154```
155
156[EnumOrdinalCodec] stores enum constants as an `int` representing their [ordinal]:
157
158```java
159enum State {INIT, RUNNING, STOPPING, STOPPED}
160
161cluster.getConfiguration().getCodecRegistry()
162 .register(new EnumOrdinalCodec<State>(State.class));
163
164// schema: create table ordinal_example(id int PRIMARY KEY, state int)
165session.execute("insert into ordinal_example (id, state) values (1, ?)", State.INIT);
166// state saved as 0
167```
168
169Note that if you registered an `EnumNameCodec` and an `EnumOrdinalCodec` _for the same enum_ at the same time, there could be a problem when executing [simple statements](../../statements/simple/), because in a simple statement, the target CQL type of a given query parameter is not known in advance, so the driver, on a best-effort attempt, will pick one or the other, whichever was registered first. If the chosen codec proves to be the wrong one, the request would fail on the server side.
170
171In practice, this is unlikely to happen, because you'll probably stick to a single CQL type for a given enum type;
172however, if you ever run into that issue, the workaround is to use [prepared statements](../../statements/prepared/), for which the driver knows the CQL type and can pick the exact codec.
173
174[EnumNameCodec]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/extras/codecs/enums/EnumNameCodec.html
175[EnumOrdinalCodec]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/extras/codecs/enums/EnumOrdinalCodec.html
176[name]: https://docs.oracle.com/javase/8/docs/api/java/lang/Enum.html#name--
177[ordinal]: https://docs.oracle.com/javase/8/docs/api/java/lang/Enum.html#ordinal--
178
179
180### JSON
181
182#### Jackson
183
184[JacksonJsonCodec] maps a Java object to a JSON string stored into a `varchar` column, using the popular [Jackson]
185library.
186
187It requires an explicit dependency on Jackson in your application:
188
189```xml
190<dependency>
191 <groupId>com.fasterxml.jackson.core</groupId>
192 <artifactId>jackson-databind</artifactId>
193 <version>2.6.3</version>
194</dependency>
195```
196
197```java
198public class User {
199 private int id;
200 private String name;
201
202 @JsonCreator
203 public User(@JsonProperty("id") int id, @JsonProperty("name") String name) {
204 this.id = id;
205 this.name = name;
206 }
207
208 ... // getters and setters
209}
210
211cluster.getConfiguration().getCodecRegistry()
212 .register(new JacksonJsonCodec<User>(User.class));
213
214// schema: create table example(id int primary key, owner varchar);
215session.execute("insert into example (id, owner) values (1, ?)",
216 new User(1, "root"));
217// owner saved as '{"id":1,"name":"root"}'
218```
219
220[JacksonJsonCodec]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/extras/codecs/json/JacksonJsonCodec.html
221[Jackson]: http://wiki.fasterxml.com/JacksonHome
222
223
224#### JSR 353
225
226[Jsr353JsonCodec] maps a [JsonStructure] to a JSON string stored into a `varchar` column, using the JSR-353 standard.
227
228It requires an explicit dependency on the JSR-353 API and an implementation:
229
230```xml
231<dependency>
232 <groupId>javax.json</groupId>
233 <artifactId>javax.json-api</artifactId>
234 <version>1.0</version>
235</dependency>
236
237<!-- Reference implementation -->
238<dependency>
239 <groupId>org.glassfish</groupId>
240 <artifactId>javax.json</artifactId>
241 <version>1.0.4</version>
242</dependency>
243```
244
245```java
246cluster.getConfiguration().getCodecRegistry()
247 .register(new Jsr353JsonCodec());
248
249// schema: create table example(id int primary key, owner varchar);
250session.execute("insert into example (id, owner) values (1, ?)",
251 javax.json.Json.createObjectBuilder()
252 .add("id", 1)
253 .add("name", "root")
254 .build());
255// owner saved as '{"id":1,"name":"root"}'
256```
257
258
259[Jsr353JsonCodec]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/extras/codecs/json/Jsr353JsonCodec.html
260[JsonStructure]: https://javaee-spec.java.net/nonav/javadocs/javax/json/JsonStructure.html
261
262
263### Optional
264
265"Optional" types provide an alternate way to represent missing values, in an attempt to avoid null pointer errors. With
266these codecs, missing values will be mapped to `NULL` in the database.
267
268#### JDK8
269
270[OptionalCodec] transforms another codec to wrap its Java type in a JDK8 [Optional].
271
272```java
273import com.datastax.driver.extras.codecs.jdk8.OptionalCodec;
274import com.google.common.reflect.TypeToken;
275import java.util.Optional;
276
277// The built-in driver codec, that maps CQL's int to Java's Integer
278TypeCodec<Integer> intCodec = TypeCodec.cint();
279
280// A codec that maps CQL's int to Java's Optional<Integer>
281OptionalCodec<Integer> optionalIntCodec = new OptionalCodec<Integer>(intCodec);
282
283cluster.getConfiguration().getCodecRegistry()
284 .register(optionalIntCodec);
285
286TypeToken<Optional<Integer>> optionalIntToken = new TypeToken<Optional<Integer>>() {};
287
288// schema: create table example (id int primary key, v int);
289PreparedStatement pst = session.prepare("insert into example (id, v) values (?, ?)");
290
291Optional<Integer> v1 = Optional.empty();
292session.execute(pst.bind()
293 .setInt("id", 1)
294 .set("v", v1, optionalIntToken));
295// v1 saved as NULL
296
297Optional<Integer> v2 = Optional.of(12);
298session.execute(pst.bind()
299 .setInt("id", 2)
300 .set("v", v2, optionalIntToken));
301// v2 saved as 12
302```
303
304This example is a bit more complex: `Optional<Integer>` is a generic type, so we can't use simple statements, because
305they select codecs according to the runtime types of their values (and we would lose the `<Integer>` part with type
306erasure).
307
308For the same reason, we need to give a type hint when setting "v", in the form of a [TypeToken]. Note that this is an
309anonymous inner class; we recommend storing these tokens as constants in a utility class, to avoid creating them too
310often.
311
312[OptionalCodec]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/extras/codecs/jdk8/OptionalCodec.html
313[Optional]: https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html
314[TypeToken]: http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/reflect/TypeToken.html
315
316#### Guava
317
318[OptionalCodec][OptionalCodec_guava] transforms another codec to wrap its Java type in a Guava
319[Optional][Optional_guava].
320
321
322```java
323import com.datastax.driver.extras.codecs.guava.OptionalCodec;
324import com.google.common.base.Optional;
325import com.google.common.reflect.TypeToken;
326
327// The built-in driver codec, that maps CQL's int to Java's Integer
328TypeCodec<Integer> intCodec = TypeCodec.cint();
329
330// A codec that maps CQL's int to Guava's Optional<Integer>
331OptionalCodec<Integer> optionalIntCodec = new OptionalCodec<Integer>(intCodec);
332
333cluster.getConfiguration().getCodecRegistry()
334 .register(optionalIntCodec);
335
336TypeToken<Optional<Integer>> optionalIntToken = new TypeToken<Optional<Integer>>() {};
337
338// schema: create table example (id int primary key, v int);
339PreparedStatement pst = session.prepare("insert into example (id, v) values (?, ?)");
340
341Optional<Integer> v1 = Optional.absent();
342session.execute(pst.bind()
343 .setInt("id", 1)
344 .set("v", v1, optionalIntToken));
345// v1 saved as NULL
346
347Optional<Integer> v2 = Optional.of(12);
348session.execute(pst.bind()
349 .setInt("id", 2)
350 .set("v", v2, optionalIntToken));
351// v2 saved as 12
352```
353
354See the JDK8 Optional section above for explanations about [TypeToken].
355
356[OptionalCodec_guava]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/extras/codecs/guava/OptionalCodec.html
357[Optional_guava]: http://docs.guava-libraries.googlecode.com/git-history/v16.0.1/javadoc/com/google/common/base/Optional.html
358
359
360### Arrays
361
362By default, the driver maps CQL lists to collections of Java objects. For high-performance scenarios, and when the
363element type maps to a Java primitive, you might want to map to an array instead, to avoid unnecessary boxing and
364unboxing.
365
366[IntArrayCodec] allows you to do that for lists of integers:
367
368```java
369cluster.getConfiguration().getCodecRegistry()
370 .register(new IntArrayCodec());
371
372// schema: create table example (i int primary key, l list<int>)
373session.execute("insert into example (i, l) values (1, ?)",
374 new int[]{1, 2, 3});
375// array saved as [1,2,3]
376```
377
378Package [com.datastax.driver.extras.codecs.arrays][arrays] contains similar codecs for all primitive types, and
379[ObjectArrayCodec] to map arrays of objects.
380
381[IntArrayCodec]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/extras/codecs/arrays/IntArrayCodec.html
382[ObjectArrayCodec]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/extras/codecs/arrays/ObjectArrayCodec.html
383[arrays]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/extras/codecs/arrays/package-summary.html
384
385### Abstract utilities
386
387The module provides two abstract classes that act as building blocks for your own codecs:
388
389[MappingCodec] is useful when you can easily convert your Java type to another type that already has a codec.
390For example, if you have a `Price` object that translates to a plain `Integer`, you can piggyback on the built-in
391integer codec, and you'll only have to write two simple conversion methods:
392
393```java
394public static class PriceCodec extends MappingCodec<Price, Integer> {
395 public PriceCodec() { super(TypeCodec.cint(), Price.class); }
396
397 @Override
398 protected Integer serialize(Price value) { ... }
399
400 @Override
401 protected Price deserialize(Integer value) { ... }
402}
403```
404
405For a more detailed example, you can look at the `OptionalCodec` implementations in the source code.
406
407[ParsingCodec] is similar, but specialized for text columns. See `EnumNameCodec` for an example.
408
409These two classes are convenient, but since they perform conversions in two steps, extending them is not necessarily the
410optimal approach. If performance is paramount, it's better to start from scratch and convert your objects to
411`ByteBuffer` directly.
412
413[MappingCodec]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/extras/codecs/MappingCodec.html
414[ParsingCodec]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/extras/codecs/ParsingCodec.html