Search code examples
javacassandracassandra-3.0user-defined-types

How to read the UDTs from collection(for ex:list) of UDTs with cassandra-driver in java?


I have table emp(id,name,list<frozen<address>>). Here address is cassandra UDT defined as create TYPE address (hno int,street text);. I am trying to read all address's for a given id in emp using below code and I get the following error:

Exception in thread "main" com.datastax.driver.core.exceptions.CodecNotFoundException: Codec not found for requested operation: [frozen<'address'> <-> com.xyz.cassandra.address]

String query1="select * from iotbilling.emp where id=?";
PreparedStatement preparedStatement2=this.session.prepare(query1);
BoundStatement boundStatement2=preparedStatement2.bind(4);
ResultSet rs2=this.session.execute(boundStatement2);
Row row2=rs2.one();
List<address> addresses=row2.getList("adresses",address.class);
System.out.println("Addresses retrieved");
for(address adr:addresses)
    System.out.println(adr.toString());

`

Here, how to capture the list of frozen address in java code that is returned from cassandra?


Solution

  • You can read the value from row and read the metadata row by row:

    UDTValue udtData = row.getUDTValue(address);
    

    For example:

    udtData.getString("name");
    

    Update with list example

    For a list it should probably look like:

    List<UDTValue> udtDataList = row.getList("adresses", UDTValue.class)
    

    And then you can easily iterate through the list and access the fields of your data.

    Best