Elffuss BraidHub

kikocis/java-driver public

8db72a89059d · 17.7 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:
112
113```java
114ObjectMapper objectMapper = ...
115JsonCodec<MyPojo> myJsonCodec = new JsonCodec<MyPojo>(MyPojo.class, objectMapper);
116CodecRegistry myCodecRegistry = new CodecRegistry().register(myJsonCodec);
117```
118
119When you instantiate a `CodecRegistry`, it automatically registers all the default codecs used by the driver.
120This ensures that the registry will not lack of an essential codec. *You cannot deregister default codecs, only
121register new ones*.
122
123The third step is to associate your `CodecRegistry` instance with your `Cluster` instance:
124
125```java
126Cluster cluster = new Cluster.builder().withCodecRegistry(myCodecRegistry).build();
127```
128
129From now on, your codec is fully operational. It will be used every time the driver encounters
130a `MyPojo` instance when executing queries, or when you ask it to retrieve a `MyPojo` instance from a `ResultSet`.
131
132For example, here is how to save a `MyPojo` object:
133
134```java
135Cluster cluster = ...
136Session session = ...
137MyPojo myPojo = ...
138// Using SimpleStatement
139Statement stmt = session.newSimpleStatement("INSERT INTO t (id, json) VALUES (?, ?)", 42, myPojo));
140// Using the Query Builder
141BuiltStatement insertStmt = new QueryBuilder(cluster).insertInto("t")
142 .value("id", 42)
143 .value("json", myPojo);
144// Using BoundStatements
145PreparedStatement ps = session.prepare("INSERT INTO t (id, json) VALUES (?, ?)");
146BoundStatement bs1 = ps.bind(42, myPojo); // or alternatively...
147BoundStatement bs2 = ps.bind()
148 .setInt(0, 42)
149 .set(1, myPojo, MyPojo.class);
150```
151
152And here is how to retrieve a `MyPojo` object converted from a JSON document:
153
154```java
155ResultSet rows = session.execute(...);
156Row row = one();
157// Let the driver convert the string for you...
158MyPojo myPojo = row.get(1, MyPojo.class);
159// ... or retrieve the raw string if you need it
160String json = row.get(1, String.class); // row.getString(1) would have worked too
161```
162
163Tip: `Row` and `BoundStatement` have several methods to set and retrieve values.
164But if you plan to use custom codecs,
165make sure that you use preferably the `get()` and `set()` methods: they
166avoid any ambiguity by requiring the user to explicitly specify the desired Java type,
167thus forcing the driver to pick the right codec for the right task.
168
169### Support for parameterized types
170
171`get()` and `set()` can even be used to retrieve collections or other
172user-defined parameterized types; simply use the `get()` and `set()` variants that
173take Guava's [TypeToken] parameter:
174
175```java
176Row row = ...
177List<MyPojo> myPojos = row.get("jsonList", new TypeToken<List<MyPojo>>(){});
178// or alternatively, the following also works for collections:
179List<MyPojo> myPojos = row.getList("jsonList", MyPojo.class);
180```
181
182### Support for collections, user types, tuples and Java Enums
183
184`CodecRegistry` instances not only store default codecs and user-defined codecs;
185they can also create new codecs on the fly, based on the set of codecs they currently hold.
186
187* Codecs for [UserType] instances are created on the fly using [UDTCodec];
188* Codecs for [TupleType] instances are created on the fly using [TupleCodec];
189* Codecs for Java Enums are created on the fly using [EnumStringCodec];
190* Codecs for collections are created on the fly using [ListCodec],
191 [SetCodec] and [MapCodec], if their element types can be handled by
192 existing codecs (or codecs that can themselves be generated).
193
194This way, the user does not have to manually register all derived codecs for a given "base" codec.
195However, other combinations of Java and CQL types not listed above cannot have their codecs created on the fly;
196such codecs must be manually registered.
197
198The driver also provides another codec for Enums that converts Enum instances to CQL ints
199representing their ordinal position: [EnumIntCodec]. If you plan to use this codec, make sure to register it
200manually, otherwise Enums would be converted using [EnumStringCodec].
201_It is not possible to mix both codecs in the same `CodecRegistry`_.
202
203Note that the default set of codecs has no support for
204[Cassandra custom types][AbstractType];
205to be able to deserialize values of such types, you need to manually register an appropriate codec.
206
207### Using custom codecs with user types and tuples
208
209By default, the driver maps user-defined type values and tuple values to [UDTValue] and [TupleValue],
210using the built-in codecs [UDTCodec] and [TupleCodec] respectively.
211
212If you want to register a custom codec for a specific user type, follow these steps:
213
214Let's suppose you have a keyspace containing the following type and table:
215
216```sql
217CREATE TYPE address (street VARCHAR, zipcode INT);
218CREATE TABLE users (id UUID PRIMARY KEY, name VARCHAR, address frozen<address>);
219```
220
221And let's suppose that you want to map the type `address` to an `Address` class:
222
223```java
224public class Address {
225
226 private final String street;
227
228 private final int zipcode;
229
230 public Address(String street, int zipcode) {
231 this.street = street;
232 this.zipcode = zipcode;
233 }
234
235 // getters, setters, equals() and hashcode() omitted
236}
237```
238
239First of all, create a codec for this class:
240
241```java
242public class AddressCodec extends TypeCodec.MappingCodec<Address, UDTValue> {
243
244 private final UserType userType;
245
246 public AddressCodec(TypeCodec<UDTValue> innerCodec, Class<Address> javaType) {
247 super(innerCodec, javaType);
248 userType = (UserType) innerCodec.getCqlType();
249 }
250
251 @Override
252 protected Address deserialize(UDTValue value) {
253 return value == null ? null : new Address(value.getString("street"), value.getInt("zipcode"));
254 }
255
256 @Override
257 protected UDTValue serialize(Address address) {
258 return address == null ? null : userType.newValue().setString("street", address.getStreet()).setInt("zipcode", address.getZipcode());
259 }
260}
261```
262
263Again, the driver provides a convenient base class: [MappingCodec].
264
265Now, create your `CodecRegistry` and `Cluster` instances the usual way:
266
267```java
268CodecRegistry codecRegistry = new CodecRegistry();
269Cluster cluster = Cluster.builder()
270 .addContactPoints(...)
271 .withCodecRegistry(codecRegistry)
272 .build();
273```
274
275Now, retrieve the metadata for type `address`:
276
277```java
278UserType addressType = cluster.getMetadata().getKeyspace(...).getUserType("address");
279```
280
281And finally, register your `AddressCodec` with the `CodecRegistry`. Note that
282your codec simply delegates the hard work to an inner codec that knows how to deal with
283user type values:
284
285```java
286AddressCodec addressCodec = new AddressCodec(new TypeCodec.UDTCodec(addressType), Address.class);
287codecRegistry.register(addressCodec);
288```
289
290And voilà! You can now retrieve `address` values as `Address` instances:
291
292```java
293ResultSet rows = session.execute(...);
294Row row = rows.one();
295// let the driver convert it for you...
296Address address = row.get("address", Address.class);
297// ...or access the low-level UDTValue, if you need
298UDTValue addressUdt = row.get("address", UDTValue.class); // row.getUDTValue("address") would have worked too
299```
300
301Note that this solution creates an intermediary `UDTValue` object when
302serializing and deserializing. It's possible to bypass this step with a
303lower-level implementation that manipulates the binary stream directly.
304That's also how the object mapper handles UDTs, and you can rely on the
305mapper to generate UDT codecs for you; see
306[this page](object_mapper/custom_codecs/#implicit-udt-codecs) for more
307information.
308
309### Limitations
310
311#### Generics
312
313Java generic types are fully supported, through Guava's [TypeToken] API.
314Be sure to only use `get()` and `set()` methods
315that take a `TypeToken` argument:
316
317```java
318// this works
319Foo<Bar> foo = row.get(0, new TypeToken<Foo<Bar>>(){})
320// this does not work due to type erasure
321Foo<Bar> foo = row.get(0, Foo.class);
322```
323
324#### Type inheritance
325
326If a codec accepts a Java type that is assignable to the
327desired Java type, that codec may be returned if it is found first
328in the registry, *even if another codec is a better match*.
329
330As a consequence, type inheritance and interfaces should be used with care.
331Let's consider an example and assume that class `B` extends class `A`:
332
3331) If you register a codec for `A`, you can pass `B` as the target type,
334because `B` instances are assignable to `A`, and the driver is capable
335of detecting that:
336
337```java
338codecRegistry.register(new ACodec());
339// all work
340A a1 = row.get(0, A.class);
341B b = row.get(0, B.class);
342A a2 = row.get(0, B.class);
343```
344
345However, because `List<B>` is *not* assignable to `List<A>`:
346
347```java
348codecRegistry.register(new ACodec());
349// this works
350List<A> as1 = row.getList(0, A.class);
351// but this throws CodecNotFoundException
352List<B> bs = row.getList(0, B.class);
353List<? extends A> as2 = row.getList(0, B.class);
354```
355
3562) If you register a codec for `B`, you can't pass `A` as the target type,
357because no codec matches `A.class` exactly:
358
359```java
360codecRegistry.register(new BCodec());
361// this works
362A a1 = row.get(0, B.class);
363B b = row.get(0, B.class);
364// but this throws CodecNotFoundException
365A a2 = row.get(0, A.class);
366// and with collections, this works
367List<B> bs = row.getList(0, B.class);
368// but this throws CodecNotFoundException
369List<A> as = row.getList(0, A.class);
370```
371
372The same apply for interfaces.
373
374### Performance considerations
375
376A codec lookup operation may be costly; to mitigate this, the `CodecRegistry` caches lookup results whenever possible.
377
378The following situations are exceptions where it is not possible to cache lookup results:
379
380* With [SimpleStatement] and [BuiltStatement] (Query Builder) instances; in these places, the driver has
381 no way to determine the right CQL type to use, so it performs a best-effort heuristic to guess which codec to use.
382* When using "ambiguous" methods of `BoundStatement` and `Row`, such as [setList()][setList],
383 [setSet()][setSet], [setMap()][setMap], [setObject()][setObject];
384 these methods are "ambiguous" because they do not convey enough compile-time information about the object
385 to serialize, so the driver performs the same heuristic to guess which codec to use.
386
387Beware that in these cases the lookup performs in average 10x worse. If performance is a key factor for your application,
388consider using prepared statements all the time, and avoid calling ambiguous methods (prefer `get()` and `set()`).
389
390[JAVA-721]: https://datastax-oss.atlassian.net/browse/JAVA-721
391[TypeCodec]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/TypeCodec.html
392[LocalDate]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/LocalDate.html
393[serialize]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/TypeCodec.html#serialize(T,%20com.datastax.driver.core.ProtocolVersion)
394[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)
395[TypeCodec.format]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/TypeCodec.html#format(T)
396[TypeCodec.parse]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/TypeCodec.html#parse(java.lang.String)
397[CodecRegistry]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/CodecRegistry.html
398[Jackson]: http://wiki.fasterxml.com/JacksonHome
399[AbstractType]: https://github.com/apache/cassandra/blob/trunk/src/java/org/apache/cassandra/db/marshal/AbstractType.java
400[EnumStringCodec]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/TypeCodec.EnumStringCodec.html
401[EnumIntCodec]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/TypeCodec.EnumIntCodec.html
402[UserType]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/UserType.html
403[UDTValue]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/UDTValue.html
404[UDTCodec]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/TypeCodec.UDTCodec.html
405[TupleType]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/TupleType.html
406[TupleValue]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/TupleValue.html
407[TupleCodec]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/TypeCodec.TupleCodec.html
408[ListCodec]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/TypeCodec.ListCodec.html
409[SetCodec]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/TypeCodec.SetCodec.html
410[MapCodec]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/TypeCodec.MapCodec.html
411[TypeToken]: http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/reflect/TypeToken.html
412[MappingCodec]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/TypeCodec.MappingCodec.html
413[StringParsingCodec]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/TypeCodec.StringParsingCodec.html
414[SimpleStatement]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/SimpleStatement.html
415[BuiltStatement]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/BuiltStatement.html
416[setList]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/SettableByIndexData.html#setList(int,%20java.util.List)
417[setSet]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/SettableByIndexData.html#setSet(int,%20java.util.Set)
418[setMap]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/SettableByIndexData.html#setMap(int,%20java.util.Map)
419[setObject]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/SettableByIndexData.html#setObject(int,%20V)