Last year I started learning Kotlin and I was surprised at how easy it was to convert a Java application. IntelliJ and a few other IDEs offer nice tools for automatic conversion, and with a few adjustments you can end up with a much more concise and less error-prone code.

So, I decided to create a sample application to show my new favorite combination: Kotlin, Spring Boot, Spring Data, and Couchbase:

Creating a User Profile Service

Puede clonar el proyecto completo aquí:

https://github.com/couchbaselabs/try-cb-kotlin

Let’s start by creating our main class:

 Nota: You class must be abra otherwise you will end up with the following error:

Here is our User entity, it is very similar to the Java one:

  • @Document: Couchbase’s annotation which defines an entity, similar to @Entity in JPA. Couchbase will automatically add a property called Clase in the document to use it as the document type.
  • @Id: The document’s key
  • @Field: Couchbase’s annotations, similar to JPA’s @Column. It is not mandatory, but we do recommend using it.

Mapping attributes in Couchbase are really simple. They will be directly mapped to the correspondent structure in JSON:

  • Simple Properties: Straightforward mapping to JSON:

  • Arrays: As you might expect, arrays like securityRoles will be converted to JSON arrays: 

 

  • Nested Entities: Do you hate to map @ManyToOne relationships? Me too. As we are using a document database, there is no need to write these relationships anymore, nested entities are also directly translated to JSON.

Repositories

Now, let’s take a look at how our repository will look like:

 

  • @N1qlPrimaryIndexed: This anotación makes sure that the bucket associated with the current repository will have a N1QL primary index
  • @ViewIndexed:  Este anotación le permite definir el nombre del documento de diseño y el nombre de la vista, así como una función de mapa y reducción personalizada.

As you can see below, you can leverage all Spring Data keywords to query the database, such as FindByBetweenIsGreaterThanLike, Existeetc.

The repository is extending CouchbasePagingAndSortingRepository, which allows you to paginate your queries by simply adding a Pageable param at the end of your method definition. If you need to write more powerful queries, you can also use N1QL:

The queries above have a few syntax-sugars to make it smaller:

  • #(#n1ql.bucket): Use this syntax avoids hard-coding the bucket name in your query
  • #{#n1ql.selectEntity}: syntax-sugar to SELECT * FROM #(#n1ql.bucket):
  • #{#n1ql.filter}: syntax-sugar to filter the document by type, technically it means class = ‘myPackage.MyClassName’ (Clase is the attribute automatically added to the document to define its type when you are working with Couchbase on Spring Data )
  • #{#n1ql.fields} will be replaced by the list of fields (eg. for a SELECT clause) necessary to reconstruct the entity.
  • #{#n1ql.delete} will be replaced by the delete from statement.
  • #{#n1ql.returning} will be replaced by returning clause needed for reconstructing entity.

Servicios

Our service is basically forwarding requests to our repository, but if you need to write ad-hoc queries, here is the right place:

Controladores

Finally, let’s also add a controller to test our services via rest:

Writing Integration Tests with Kotlin

To run the integrations tests correctly, don’t forget to configure the credentials of your database in the aplicación.propiedades file:

Here, you can see how our tests look like:

Kotlin and Maven Dependencies

Kotlin is moving quickly, so be aware to use the most recent versions of each dependency:

You can view the whole pom.xml aquí.

Autor

Publicado por Denis Rosa, Defensor del Desarrollador, Couchbase

Denis Rosa es un Developer Advocate para Couchbase y vive en Munich - Alemania. Tiene una sólida experiencia como ingeniero de software y habla con fluidez Java, Python, Scala y Javascript. A Denis le gusta escribir sobre búsqueda, Big Data, AI, Microservicios y todo lo que pueda ayudar a los desarrolladores a hacer una aplicación hermosa, más rápida, estable y escalable.

Dejar una respuesta