Apache Cassandra With Java: Introduction to UDT
The Apache Cassandra User-defined types (UDTs) might be beneficial to the Java programming model. In this post, we'll explore how to take advantage of it.
Join the DZone community and get the full member experience.Join For Free
Apache Cassandra User-defined types (UDTs) can attach multiple data fields, each named and typed, to a single column. The fields used to create a UDT may be any valid data type, including collections and other existing UDTs. Once created, UDTs may be used to define a column in a table. In this post, we'll explore how to use Cassandra's feature with Java.
In simple words, UDT is a type where you can get as much information as you can; for example, give e-commerce in the column family product, there is the option to create a UDT Money where the data are the currency with the value.
Before, go further in detail on Apache Cassandra UDT, it essential to highlight that Cassandra is not a relational database. Thus, denormalization is your friend, and Cassandra does not have the support to
left join.The model should follow the query-driven modeling instead of the normalization.
This tutorial will create a
Company entity to explore the UDT feature. This Company entity has five fields:
- The company's name.
- The company's cost, where it will create a Money type.
- The languages that the company speaks.
- The company's contact in the social media.
- The headquarter, a set of a Headquarter with city and country.
Cassandra is not schemeless. Thus, it is natural to create the structure before using this. So, the script below is a CQL to create the types,
headquarter, then the
Company as column family.
In the Cassandra integration with Java, this tutorial uses Jakarta NoSQL once it is a standard to Jakarta EE specification.
The UDT creation isn't different from a normal entity; therefore, it will use the Entity and Column annotations, similar to JPA.
Money types have two fields one represents the currency and the amount. Java has a specific kind to describes coin, the Currency class. Once Cassandra does not support it, we'll create a convert to move this class data to String.
The types of models are ready to use in the Company class. This entity will have trivial annotations such as
Column. Furthermore, there is an annotation to identify whose that entity is a UDT. The UDT annotation requires an attribute to define the type name.
Company class is ready to use. The next step is storage and retrieves information using the
CassandraTemplate. As with any service, make sure that there is a Cassandra instance running. The easiest way is with docker with the command below:
In this tutorial, we talked about Cassandra's UDT feature and how to use it as a collection or a single field with Jakarta NoSQL.
Opinions expressed by DZone contributors are their own.