Elffuss BraidHub

kikocis/java-driver public

cf32ad67f65d · 18.2 KiBRenderedRawPermalink
1## Custom Codecs
2
3Custom codecs support transparent, user-configurable mapping of CQL types to arbitrary Java objects.
4
5Practical use cases that justify such a feature are numerous:
6
7* Ability to map CQL timestamp, date and time columns to Java 8 or Joda Time classes (rather than the built-in mappings for Date, [LocalDate] and Long);
8* Ability to map CQL varchar columns directly to JSON or XML mapped objects (i.e. using frameworks such as Jackson);
9* Ability to map CQL user-defined types to Java objects;
10* Ability to map CQL lists directly to Java arrays;
11* Ability to map CQL collections directly to Scala collections;
12* etc.
13
14### Overview of the serialization mechanism
15
16The central piece in the serialization mechanism is [TypeCodec].
17
18Each `TypeCodec` supports a bidirectional mapping between a Java type and a CQL type. A `TypeCodec` is thus capable of 4 basic operations:
19
20* [Serialize][serialize] a Java object into a CQL value;
21* [Deserialize][deserialize] a CQL value into a Java object;
22* [Format][TypeCodec.format] a Java object into a CQL literal;
23* [Parse][TypeCodec.parse] a CQL literal into a Java object.
24
25Additionally, it implements inspection methods that verify if the codec is suitable for a specific
26CQL type and/or Java object.
27
28`TypeCodec` can be freely subclassed by users willing to implement their own serialization logic.
29However, users are only required to do so when they want to extend
30the driver's default set of codecs by registering additional codecs that handle
31Java types that the driver is otherwise unable to process. For all other users,
32the built-in set of codecs that is bundled with the driver provides
33exactly the same functionality that the driver used to offer so far,
34with out-of-the-box conversion from all CQL types to standard Java equivalents.
35
36Refer to the [javadocs][TypeCodec] of `TypeCodec` for more information.
37
38`TypeCodec`s are centralized in a [CodecRegistry] instance.
39Whenever the driver needs to perform one of the aforementioned operations,
40it will lookup for an appropriate codec in a `CodecRegistry`.
41`CodecRegistry` is also used to manually register user-created codecs (see below for detailed instructions).
42It also caches codec lookup results for faster execution whenever possible.
43
44Refer to the [javadocs][CodecRegistry] of User `CodecRegistry` for more information.
45
46### Implementing and using custom codecs
47
48Let's consider the following scenario: a user has JSON documents stored in a varchar column, and wants
49the driver to automatically map that column to a Java object using the [Jackson] library,
50instead of returning the raw JSON string.
51
52The (admittedly simplistic) table structure is as follows:
53
54```sql
55CREATE TABLE t (id int PRIMARY KEY, json VARCHAR);
56```
57
58The first step is to implement a suitable codec. Using Jackson, here is what a Json codec could like like:
59
60```java
61/**
62 * A simple Json codec.
63 */
64public class JsonCodec<T> extends TypeCodec.StringParsingCodec<T> {
65
66 private final ObjectMapper objectMapper;
67
68 public JsonCodec(Class<T> javaType, ObjectMapper objectMapper) {
69 super(javaType);
70 this.objectMapper = objectMapper;
71 }
72
73 @Override
74 @SuppressWarnings("unchecked")
75 public T fromString(String value) {
76 if (value == null)
77 return null;
78 try {
79 return (T) objectMapper.readValue(value, getJavaType().getRawType());
80 } catch (IOException e) {
81 throw new InvalidTypeException(e.getMessage(), e);
82 }
83 }
84
85 @Override
86 public String toString(T value) {
87 if (value == null)
88 return null;
89 try {
90 return objectMapper.writeValueAsString(value);
91 } catch (JsonProcessingException e) {
92 throw new InvalidTypeException(e.getMessage(), e);
93 }
94 }
95}
96```
97
98As you can see, the driver already provides a convenient base class: [StringParsingCodec][StringParsingCodec].
99
100A few implementation guidelines:
101
102* Your codecs should be thread-safe, or better yet, immutable;
103* Your codecs should be fast: do not forget that codecs are executed often and are usually very "hot" pieces of code;
104* Your codecs should never block.
105
106Note: the code above is an example and is not particularly efficient;
107it suffers from the overhead of deserializing raw bytes into a String,
108to only then parse the String into an object.
109More advanced solutions that read the underlying byte stream directly are possible.
110
111The second step is to register your codec with a `CodecRegistry` instance:
112
113```java
114ObjectMapper objectMapper = ...
115JsonCodec<MyPojo> myJsonCodec = new JsonCodec<MyPojo>(MyPojo.class, objectMapper);
116CodecRegistry myCodecRegistry = cluster.getConfiguration().getCodecRegistry();
117myCodecRegistry.register(myJsonCodec);
118```
119
120As you can see, the easiest way to do so is to access the `Cluster`'s `CodecRegistry`.
121By default, `Cluster` instances will use `CodecRegistry.DEFAULT_INSTANCE`,
122which should be adequate for most users.
123
124It is however possible to create a `Cluster` using a different `CodecRegistry`:
125
126```java
127CodecRegistry myCodecRegistry = new CodecRegistry();
128Cluster cluster = new Cluster.builder().withCodecRegistry(myCodecRegistry).build();
129```
130
131Note: when you instantiate a new `CodecRegistry`, it automatically registers all the default codecs used by the driver.
132This ensures that the new registry will not lack of an essential codec. *You cannot deregister default codecs, only
133register new ones*.
134
135From now on, your custom codec is fully operational. It will be used every time the driver encounters
136a `MyPojo` instance when executing queries, or when you ask it to retrieve a `MyPojo` instance from a `ResultSet`.
137
138For example, here is how to save a `MyPojo` object:
139
140```java
141Cluster cluster = ...
142Session session = ...
143MyPojo myPojo = ...
144// Using SimpleStatement
145Statement stmt = session.newSimpleStatement("INSERT INTO t (id, json) VALUES (?, ?)", 42, myPojo));
146// Using the Query Builder
147BuiltStatement insertStmt = new QueryBuilder(cluster).insertInto("t")
148 .value("id", 42)
149 .value("json", myPojo);
150// Using BoundStatements
151PreparedStatement ps = session.prepare("INSERT INTO t (id, json) VALUES (?, ?)");
152BoundStatement bs1 = ps.bind(42, myPojo); // or alternatively...
153BoundStatement bs2 = ps.bind()
154 .setInt(0, 42)
155 .set(1, myPojo, MyPojo.class);
156```
157
158And here is how to retrieve a `MyPojo` object converted from a JSON document:
159
160```java
161ResultSet rows = session.execute(...);
162Row row = one();
163// Let the driver convert the string for you...
164MyPojo myPojo = row.get(1, MyPojo.class);
165// ... or retrieve the raw string if you need it
166String json = row.get(1, String.class); // row.getString(1) would have worked too
167```
168
169Tip: `Row` and `BoundStatement` have several methods to set and retrieve values.
170But if you plan to use custom codecs,
171make sure that you use preferably the `get()` and `set()` methods: they
172avoid any ambiguity by requiring the user to explicitly specify the desired Java type,
173thus forcing the driver to pick the right codec for the right task.
174
175### Support for parameterized types
176
177`get()` and `set()` can even be used to retrieve collections or other
178user-defined parameterized types; simply use the `get()` and `set()` variants that
179take Guava's [TypeToken] parameter:
180
181```java
182Row row = ...
183List<MyPojo> myPojos = row.get("jsonList", new TypeToken<List<MyPojo>>(){});
184// or alternatively, the following also works for collections:
185List<MyPojo> myPojos = row.getList("jsonList", MyPojo.class);
186```
187
188### Support for collections, user types, tuples and Java Enums
189
190`CodecRegistry` instances not only store default codecs and user-defined codecs;
191they can also create new codecs on the fly, based on the set of codecs they currently hold.
192
193* Codecs for [UserType] instances are created on the fly using [UDTCodec];
194* Codecs for [TupleType] instances are created on the fly using [TupleCodec];
195* Codecs for Java Enums are created on the fly using [EnumStringCodec];
196* Codecs for collections are created on the fly using [ListCodec],
197 [SetCodec] and [MapCodec], if their element types can be handled by
198 existing codecs (or codecs that can themselves be generated).
199
200This way, the user does not have to manually register all derived codecs for a given "base" codec.
201However, other combinations of Java and CQL types not listed above cannot have their codecs created on the fly;
202such codecs must be manually registered.
203
204The driver also provides another codec for Enums that converts Enum instances to CQL ints
205representing their ordinal position: [EnumIntCodec]. If you plan to use this codec, make sure to register it
206manually, otherwise Enums would be converted using [EnumStringCodec].
207_It is not possible to mix both codecs in the same `CodecRegistry`_.
208
209Note that the default set of codecs has no support for
210[Cassandra custom types][AbstractType];
211to be able to deserialize values of such types, you need to manually register an appropriate codec.
212
213### Using custom codecs with user types and tuples
214
215By default, the driver maps user-defined type values and tuple values to [UDTValue] and [TupleValue],
216using the built-in codecs [UDTCodec] and [TupleCodec] respectively.
217
218If you want to register a custom codec for a specific user type, follow these steps:
219
220Let's suppose you have a keyspace containing the following type and table:
221
222```sql
223CREATE TYPE address (street VARCHAR, zipcode INT);
224CREATE TABLE users (id UUID PRIMARY KEY, name VARCHAR, address frozen<address>);
225```
226
227And let's suppose that you want to map the type `address` to an `Address` class:
228
229```java
230public class Address {
231
232 private final String street;
233
234 private final int zipcode;
235
236 public Address(String street, int zipcode) {
237 this.street = street;
238 this.zipcode = zipcode;
239 }
240
241 // getters, setters, equals() and hashcode() omitted
242}
243```
244
245First of all, create a codec for this class:
246
247```java
248public class AddressCodec extends TypeCodec.MappingCodec<Address, UDTValue> {
249
250 private final UserType userType;
251
252 public AddressCodec(TypeCodec<UDTValue> innerCodec, Class<Address> javaType) {
253 super(innerCodec, javaType);
254 userType = (UserType) innerCodec.getCqlType();
255 }
256
257 @Override
258 protected Address deserialize(UDTValue value) {
259 return value == null ? null : new Address(value.getString("street"), value.getInt("zipcode"));
260 }
261
262 @Override
263 protected UDTValue serialize(Address address) {
264 return address == null ? null : userType.newValue().setString("street", address.getStreet()).setInt("zipcode", address.getZipcode());
265 }
266}
267```
268
269Again, the driver provides a convenient base class: [MappingCodec].
270
271Now (and only if you intend to use your own `CodecRegistry`),
272create it and register it on your `Cluster` instance:
273
274```java
275// only if you do not intend to use CodecRegistry.DEFAULT_INSTANCE
276CodecRegistry codecRegistry = new CodecRegistry();
277Cluster cluster = Cluster.builder()
278 .addContactPoints(...)
279 .withCodecRegistry(codecRegistry)
280 .build();
281```
282
283Now, retrieve the metadata for type `address`:
284
285```java
286UserType addressType = cluster.getMetadata().getKeyspace(...).getUserType("address");
287```
288
289And finally, register your `AddressCodec` with the `CodecRegistry`. Note that
290your codec simply delegates the hard work to an inner codec that knows how to deal with
291user type values:
292
293```java
294AddressCodec addressCodec = new AddressCodec(new TypeCodec.UDTCodec(addressType), Address.class);
295codecRegistry.register(addressCodec);
296```
297
298And voilà! You can now retrieve `address` values as `Address` instances:
299
300```java
301ResultSet rows = session.execute(...);
302Row row = rows.one();
303// let the driver convert it for you...
304Address address = row.get("address", Address.class);
305// ...or access the low-level UDTValue, if you need
306UDTValue addressUdt = row.get("address", UDTValue.class); // row.getUDTValue("address") would have worked too
307```
308
309Note that this solution creates an intermediary `UDTValue` object when
310serializing and deserializing. It's possible to bypass this step with a
311lower-level implementation that manipulates the binary stream directly.
312That's also how the object mapper handles UDTs, and you can rely on the
313mapper to generate UDT codecs for you; see
314[this page](../object_mapper/custom_codecs/#implicit-udt-codecs) for more
315information.
316
317### Limitations
318
319#### Generics
320
321Java generic types are fully supported, through Guava's [TypeToken] API.
322Be sure to only use `get()` and `set()` methods
323that take a `TypeToken` argument:
324
325```java
326// this works
327Foo<Bar> foo = row.get(0, new TypeToken<Foo<Bar>>(){})
328// this does not work due to type erasure
329Foo<Bar> foo = row.get(0, Foo.class);
330```
331
332#### Type inheritance
333
334If a codec accepts a Java type that is assignable to the
335desired Java type, that codec may be returned if it is found first
336in the registry, *even if another codec is a better match*.
337
338As a consequence, type inheritance and interfaces should be used with care.
339Let's consider an example and assume that class `B` extends class `A`:
340
3411) If you register a codec for `A`, you can pass `B` as the target type,
342because `B` instances are assignable to `A`, and the driver is capable
343of detecting that:
344
345```java
346codecRegistry.register(new ACodec());
347// all work
348A a1 = row.get(0, A.class);
349B b = row.get(0, B.class);
350A a2 = row.get(0, B.class);
351```
352
353However, because `List<B>` is *not* assignable to `List<A>`:
354
355```java
356codecRegistry.register(new ACodec());
357// this works
358List<A> as1 = row.getList(0, A.class);
359// but this throws CodecNotFoundException
360List<B> bs = row.getList(0, B.class);
361List<? extends A> as2 = row.getList(0, B.class);
362```
363
3642) If you register a codec for `B`, you can't pass `A` as the target type,
365because no codec matches `A.class` exactly:
366
367```java
368codecRegistry.register(new BCodec());
369// this works
370A a1 = row.get(0, B.class);
371B b = row.get(0, B.class);
372// but this throws CodecNotFoundException
373A a2 = row.get(0, A.class);
374// and with collections, this works
375List<B> bs = row.getList(0, B.class);
376// but this throws CodecNotFoundException
377List<A> as = row.getList(0, A.class);
378```
379
380The same apply for interfaces.
381
382### Performance considerations
383
384A codec lookup operation may be costly; to mitigate this, the `CodecRegistry` caches lookup results whenever possible.
385
386The following situations are exceptions where it is not possible to cache lookup results:
387
388* With [SimpleStatement] instances and [BuiltStatement] instances (created via the Query Builder); in these places, the driver has
389 no way to determine the right CQL type to use, so it performs a best-effort heuristic to guess which codec to use.
390* When using "ambiguous" methods of `BoundStatement` and `Row`, such as [setList()][setList],
391 [setSet()][setSet], [setMap()][setMap], [setObject()][setObject];
392 these methods are "ambiguous" because they do not convey enough compile-time information about the object
393 to serialize, so the driver performs the same heuristic to guess which codec to use.
394
395Beware that in these cases the lookup performs in average 10x worse. If performance is a key factor for your application,
396consider using prepared statements all the time, and avoid calling ambiguous methods (prefer `get()` and `set()`).
397
398[JAVA-721]: https://datastax-oss.atlassian.net/browse/JAVA-721
399[TypeCodec]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/TypeCodec.html
400[LocalDate]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/LocalDate.html
401[serialize]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/TypeCodec.html#serialize(T,%20com.datastax.driver.core.ProtocolVersion)
402[deserialize]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/TypeCodec.html#deserialize(java.nio.ByteBuffer,%20com.datastax.driver.core.ProtocolVersion)
403[TypeCodec.format]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/TypeCodec.html#format(T)
404[TypeCodec.parse]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/TypeCodec.html#parse(java.lang.String)
405[CodecRegistry]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/CodecRegistry.html
406[Jackson]: http://wiki.fasterxml.com/JacksonHome
407[AbstractType]: https://github.com/apache/cassandra/blob/trunk/src/java/org/apache/cassandra/db/marshal/AbstractType.java
408[EnumStringCodec]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/TypeCodec.EnumStringCodec.html
409[EnumIntCodec]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/TypeCodec.EnumIntCodec.html
410[UserType]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/UserType.html
411[UDTValue]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/UDTValue.html
412[UDTCodec]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/TypeCodec.UDTCodec.html
413[TupleType]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/TupleType.html
414[TupleValue]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/TupleValue.html
415[TupleCodec]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/TypeCodec.TupleCodec.html
416[ListCodec]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/TypeCodec.ListCodec.html
417[SetCodec]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/TypeCodec.SetCodec.html
418[MapCodec]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/TypeCodec.MapCodec.html
419[TypeToken]: http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/reflect/TypeToken.html
420[MappingCodec]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/TypeCodec.MappingCodec.html
421[StringParsingCodec]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/TypeCodec.StringParsingCodec.html
422[SimpleStatement]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/SimpleStatement.html
423[BuiltStatement]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/BuiltStatement.html
424[setList]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/SettableByIndexData.html#setList(int,%20java.util.List)
425[setSet]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/SettableByIndexData.html#setSet(int,%20java.util.Set)
426[setMap]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/SettableByIndexData.html#setMap(int,%20java.util.Map)
427[setObject]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/SettableByIndexData.html#setObject(int,%20V)