Scylla Documentation Logo Documentation
  • Server
    • Scylla Open Source
    • Scylla Enterprise
    • Scylla Alternator
  • Cloud
    • Scylla Cloud
    • Scylla Cloud Docs
  • Tools
    • Scylla Manager
    • Scylla Monitoring Stack
    • Scylla Operator
  • Drivers
    • CQL Drivers
    • DynamoDB Drivers
Download
Menu
Scylla Java Driver Manual Core driver User-defined types

User-defined types¶

Quick overview¶

Ordered set of named, typed fields, e.g. { street: '1 Main St', zip: 12345}.

  • row.getUdtValue() / boundStatement.setUdtValue().

  • positional or named getters and setters: udtValue.getString("street"), udtValue.setInt(1, 12345)…

  • getting hold of the UserDefinedType:

    • statement or session metadata, or udtValue.getType().

    • UserDefinedTypeBuilder (not recommended, dangerous if you build a type that doesn’t match the database schema).

  • creating a value from a type: userDefinedType.newValue().


CQL user-defined types are ordered sets of named, typed fields. They must be defined in a keyspace:

CREATE TYPE ks.type1 (
  a int,
  b text,
  c float);

And can then be used as a column type in tables, or a field type in other user-defined types in that keyspace:

CREATE TABLE ks.collect_things (
  pk int,
  ck1 text,
  ck2 text,
  v frozen<type1>,
  PRIMARY KEY (pk, ck1, ck2)
);

CREATE TYPE ks.type2 (v frozen<type1>);

Fetching UDTs from results¶

The driver maps UDT columns to the UdtValue class, which exposes getters and setters to access individual fields by index or name:

Row row = session.execute("SELECT v FROM ks.collect_things WHERE pk = 1").one();

UdtValue udtValue = row.getUdtValue("v");
int a = udtValue.getInt(0);
String b = udtValue.getString("b");
Float c = udtValue.getFloat(2);

Using UDTs as parameters¶

Statements may contain UDTs as bound values:

PreparedStatement ps =
  session.prepare(
      "INSERT INTO ks.collect_things (pk, ck1, ck2, v) VALUES (:pk, :ck1, :ck2, :v)");

To create a new UDT value, you must first have a reference to its UserDefinedType. There are various ways to get it:

  • from the statement’s metadata

    UserDefinedType udt = (UserDefinedType) ps.getVariableDefinitions().get("v").getType();
    
  • from the driver’s schema metadata:

    UserDefinedType udt =
        session.getMetadata()
            .getKeyspace("ks")
            .flatMap(ks -> ks.getUserDefinedType("type1"))
            .orElseThrow(() -> new IllegalArgumentException("Missing UDT definition"));
    
  • from another UDT value:

    UserDefinedType udt = udtValue.getType();
    

Note that the driver’s official API does not expose a way to build UserDefinedType instances manually. This is because the type’s internal definition must precisely match the database schema; if it doesn’t (for example if the fields are not in the same order), you run the risk of inserting corrupt data, that you won’t be able to read back. There is still a way to do it with the driver, but it’s part of the internal API:

// Advanced usage: make sure you understand the risks
import com.datastax.oss.driver.internal.core.type.UserDefinedTypeBuilder;

UserDefinedType udt =
    new UserDefinedTypeBuilder("ks", "type1")
        .withField("a", DataTypes.INT)
        .withField("b", DataTypes.TEXT)
        .withField("c", DataTypes.FLOAT)
        .build();

Note that a manually created type is detached.

Once you have the type, call newValue() and set the fields:

UdtValue udtValue = udt.newValue().setInt(0, 1).setString(1, "hello").setFloat(2, 2.3f);

// Or as a one-liner for convenience:
UdtValue udtValue = udt.newValue(1, "hello", 2.3f);

And bind your UDT value like any other type:

BoundStatement bs =
    ps.boundStatementBuilder()
        .setInt("pk", 1)
        .setString("ck1", "1")
        .setString("ck2", "1")
        .setUdtValue("v", udtValue)
        .build();
session.execute(bs);
PREVIOUS
Tuples
NEXT
Developer docs
  • 4.13.0.x
    • 4.13.0.x
    • 4.12.0.x
    • 4.11.1.x
    • 4.10.0.x
    • 4.7.2.x
    • 3.11.2.x
    • 3.11.0.x
    • 3.10.2.x
    • 3.7.2.x
  • Java Driver for Scylla and Apache Cassandra®
  • API Documentation
  • Manual
    • API conventions
    • Case sensitivity
    • Core driver
      • Address resolution
      • Asynchronous programming
      • Authentication
      • Bill of Materials (BOM)
      • Compression
      • Configuration
        • Reference configuration
      • Control connection
      • Custom codecs
      • Detachable types
      • Using the driver in GraalVM native images
      • Query idempotence
      • Integration
      • Load balancing
      • Logging
      • Metadata
        • Node metadata
        • Schema metadata
        • Token metadata
      • Metrics
      • Native protocol
      • Non-blocking programming
      • Paging
      • Performance
      • Connection pooling
      • Query timestamps
      • Reactive Style Programming
      • Reconnection
      • Request tracker
      • Retries
      • Using the shaded JAR
      • Speculative query execution
      • SSL
      • Statements
        • Batch statements
        • Per-query keyspace
        • Prepared statements
        • Simple statements
      • Temporal types
      • Request throttling
      • Query tracing
      • Tuples
      • User-defined types
    • Developer docs
      • Administrative tasks
      • Common infrastructure
        • Concurrency
        • Driver context
        • Event bus
      • Native protocol layer
      • Netty pipeline
      • Request execution
    • Mapper
      • Integration
        • Kotlin
        • Lombok
        • Java 14 Records
        • Scala
      • DAOs
        • Custom result types
        • Delete methods
        • GetEntity methods
        • Increment methods
        • Insert methods
        • Null saving strategy
        • Query methods
        • Query provider methods
        • Select methods
        • SetEntity methods
        • Statement attributes
        • Update methods
      • Entities
      • Mapper interface
    • OSGi
    • Query builder
      • Conditions
      • DELETE
      • Idempotence in the query builder
      • INSERT
      • Relations
      • Schema builder
        • Aggregate
        • Function
        • Index
        • Keyspace
        • Materialized View
        • Table
        • Type
      • SELECT
      • Terms
      • TRUNCATE
      • UPDATE
  • Upgrade guide
  • Frequently asked questions
  • Changelog
  • Create an issue
  • Edit this page

On this page

  • User-defined types
    • Quick overview
    • Fetching UDTs from results
    • Using UDTs as parameters
Logo
Docs Contact Us About Us
Mail List Icon Slack Icon
© 2022, ScyllaDB. All rights reserved.
Last updated on 25 May 2022.
Powered by Sphinx 4.3.2 & ScyllaDB Theme 1.2.2