Search code examples
javacassandradatastaxdatastax-java-driver

How can I convert a CQL literal to a java object while writing custom codec for my UDT using datastax?


I have a table in Cassandra keyspace called User which must have a UDT field called Address. The TYPE Address has been created and also the User table is created in the same keyspace. But while running the application it is asking for Codec for Address.java as following:

Codec not found for requested operation: [UDT(library.address) <-> com.mypackage.demoapp.dao.Address].

So I am trying to now create a custom codec for my Address.java class. Following is the structure of the class:

public class AddressCodec extends TypeCodec.AbstractUDTCodec<Address> {

    protected AddressCodec(UserType definition, Class<Address> javaClass) {
        super(definition, javaClass);
    }

    @Override
    protected Address newInstance() {
        return null;
    }

    @Override
    protected ByteBuffer serializeField(Address address, String s, ProtocolVersion protocolVersion) {
        return null;
    }

    @Override
    protected Address deserializeAndSetField(ByteBuffer byteBuffer, Address address, String s, ProtocolVersion protocolVersion) {
        return null;
    }

    @Override
    protected String formatField(Address address, String s) {
        return null;
    }

    @Override
    protected Address parseAndSetField(String input, Address address, String fieldName) {
        return null;
    }
}

However, I am not understanding how to map/serialize/de-serialize between the CQL fields and Java fields of Address. Some explanation or example code would be very helpful.

NOTE: I AM NOT USING SPRING FRAMEWORK, AND NOT LOOKING FOR ANY SPRING ORIENTED CONFIGURATION TECHNIQUES.

Thanks.


Solution

  • for Java driver 3, instead of using TypedCodec.AbstractUDTCodec just follow the driver documentation on codecs, and implement your codec as following:

    • Copy the whole source code of the AddressCodec in the documentation
    • adjust toAddress and toUDTValue functions to get/set necessary fields of your POJO

    For Java driver 4.x, with Object Mapper, just annotate your POJO with @Entity (add @CqlName if necessary, when of POJO is different than name of UDT). See documentation on it.