How we use Kotlin with Exposed at TouK

Why Kotlin? At TouK, we try to early adopt technologies. We don’t have a starter project skeleton that is reused in every new project, we want to try something that fits the project needs, even if it’s not that popular yet. We tried Kotlin first it mid 2016, right after reaching 1.0.2 version

Why Kotlin?

At TouK, we try to early adopt technologies. We don’t have a starter project skeleton reused in every new project; we want to try something that fits the project’s needs, even if it’s not that popular yet. We tried Kotlin first in mid-2016, right after reaching the 1.0.2 version. It was getting really popular in Android development, but almost nobody used it on the backend, especially — with production deployment. After reading some “hello world” examples, including this great article by Sebastien Deleuze we decided to try Kotlin as main language for a new MVNO project. The project was mainly a backend for a mobile app, with some integrations with external services (chat, sms, payments) and background tasks regarding customer subscriptions. We felt that Kotlin would be something fresh and more pleasant for developers, but we also liked the “not reinventing the wheel” approach — reusing large parts of the Java/JVM ecosystem we were happy with for existing projects (Spring, Gradle, JUnit, Mockito).

Why Exposed?

We initially felt that Kotlin + JPA/Hibernate is not a perfect match. Kotlin’s functional nature with first-class immutability support was not something that could seemly integrate with full-blown ORM started in the pre-Java8 era. But Sebastien’s article led us to try Exposed — a SQL access library maintained by JetBrains. From the beginning, we really liked the main assumptions of Exposed:

  • not trying to be full ORM framework
  • two flavors — typesafe SQL DSL and DAO/ActiveRecord style
  • lightweight, no reflection
  • no code generation
  • Spring integration
  • no annotations on your domain classes (in SQL DSL flavor)
  • open for extension (e.g. PostGIS and new DB dialects)

TL;DR

If you want to see how we use Kotlin + Exposed duo in our projects, check out this Github repo. It’s a Spring Boot app exposing REST API with the implementation of Medium clone as specified in http://realworld.io (“The mother of all demo apps”).

Another nice example is this repo by Seb Schmidt.

SQL DSL

In our projects we decided to try the “typesafe SQL DSL” flavor of Exposed. In this approach you don’t have to add anything to your domain classes, just need to write a simple schema mapping using Kotlin in configuration-as-code manner:

data class User(
  val username: Username,
  val password: String,
  val email: String
)

object UserTable : Table("users") {
    val username = text("username")
    val email = text("email")
    val password = text("password")
}

And then you can write type/null-safe queries with direct mapping to your domain classes:

UserTable.select { UserTable.username eq username }?.toUser()

// or 

UserTable.select { UserTable.username like username }.map { it.toUser() }

fun ResultRow.toUser() = User(
       username = this[UserTable.username],
       email = this[UserTable.email],
       password = this[UserTable.password]
)

RefIds

We like type-safe RefIds in our domain code. This is particularly useful in DDD-ish architectures, where you can keep those RefIds in a shared domain and use them to communicate between contexts.

So we wrap plan ids (longs, strings) into simple wrapper classes (e.g. UserId, ArticleId, Username, Slug). Exposed allows to easily register your own column types or even generic WrapperColumnType implementation that you can find in our repo.

Using this technique you can rewrite this mapping to something like this:

sealed class UserId : RefId<Long>() {
  object New : UserId() {
    override val value: Long by IdNotPersistedDelegate<Long>()
  }
  data class Persisted(override val value: Long) : UserId() {
    override fun toString() = "UserId(value=$value)"
  }
}

data class User(
   val id: UserId = UserId.New,
   //...
)

fun Table.userId(name: String) = longWrapper<UserId>(name, UserId::Persisted, UserId::value)

object UserTable : Table("users") {
  val id = userId("id").primaryKey().autoIncrement()
//...
}

And now we can query by type-safe RefIds:

override fun findBy(userId: UserId) =
  UserTable.select { UserTable.id eq userId }?.toUser()

Relationship mapping

One of the most significant selling points of ORMs is how easy it is to deal with relations. You just annotate the related field/collection with OneToOne or OneToMany and then can fetch the whole graph of objects at once. In theory — quite a nice idea, but in practice, things often go wrong. I’m not going to dig into details, instead, I recommend you read e.g. these fragments of “Opinionated JPA with Querydsl” book:

In Exposed SQL DSL approach you have to do relationship mapping by yourself — if you need to. Let’s consider Article and Tag case from our project’s domain. We have a many-to-many relation here, so we need additional “article_tags” table:

object ArticleTagTable : Table("article_tags") {
   val tagId = tagId("tag_id").references(TagTable.id)
   val articleId = articleId("article_id").references(ArticleTable.id)
}

When creating an Article, we have to attach all the associated Tags by populating Article’s generated id into ArticleTabTable entries:

override fun create(article: Article): Article {
   val savedArticle = ArticleTable.insert { it.from(article) }
           .getOrThrow(ArticleTable.id)
           .let { article.copy(id = it) }
   savedArticle.tags.forEach { tag ->
       ArticleTagTable.insert {
           it[ArticleTagTable.tagId] = tag.id
           it[ArticleTagTable.articleId] = savedArticle.id
       }
   }
   return savedArticle
}

The funny part is the mapping of Article with Tags in query methods — in API specification Tags are always returned with the Article — so we need to eagerly fetch tags by using leftJoin:

val ArticleWithTags = (ArticleTable leftJoin ArticleTagTable leftJoin TagTable)

override fun findBy(articleId: ArticleId) =
  ArticleWithTags
    .select { ArticleTable.id eq articleId }
    .toArticles()
    .singleOrNull()

After joining, we have then one ResultRow per one Article-Tag pair, so we have to group them by ArticleId, and build the correct Article object by adding Tags for each matching resultRow:

fun Iterable<ResultRow>.toArticles(): List<ResultRow> {
   return fold(mutableMapOf<ArticleId, Article>()) { map, resultRow ->
       val article = resultRow.toArticle()
       val tagId = resultRow.tryGet(ArticleTagTable.tagId)
       val tag = tagId?.let { resultRow.toTag() }
       val current = map.getOrDefault(article.id, article)
       map[article.id] = current.copy(tags = current.tags + listOfNotNull(tag))
       map
   }.values.toList()
}

This implementation allows us to solve all the possible cases:

  • no articles (fold just returns empty map)
  • articles with no tags (tag is null, so listOfNotNull(tag) is empty)
  • articles with many tags (an article with a single tag is inserted into the map, then other tags are added in copy method)

However, consider when you need to fetch the dependent structure with the root object? For tags it makes sense since you always want the tags with the article, and the count of tags for any article should not be that huge. What about the comments? You definitely don’t want all the comments each time you fetch the article, instead you’ll need some kind of paging or even making a parent-child hierarchy for comments for the article. That’s why we recommend having this relationship mapped indirectly — every Comment should have ArticleId property, and the CommentRepository could have methods like:

fun findAllBy(articleId: ArticleId): List<Comment>
// or
fun findAllByPaged(articleId: ArticleId, pageRequest: PageRequest): Page<Comment>

Extendibility

Exposed is by design open for extension, making it even easier with Kotlin’s support for extension methods. You can define your own column type or expressions, e.g. for PostGIS point type support as Sebastian showed in his article. We used similar PostGIS extension in our project too. We were also able to implement a simple support for Java8 DateTime column type — for now, Exposed has Joda-time support, a generic approach for various date/time libraries is planned in the roadmap.

The bigger thing was Oracle DB dialect — we were forced to migrate to Oracle at some time in our project. We submitted a pull-request with foundations of Oracle 12 support, being tested in production for a while (then, we moved back to PostgreSQL…). The implementation was rather straightforward, with DataType- and FunctionProvider interfaces to provide and just a few tweaks in batch insert support.

Final thoughts

Our developer experience with Kotlin+Exposed duo was really pleasant. If you don’t plan to map many relations directly, just use simple data classes, connected by RefIds, it works really well. The Exposed library itself may need more exhaustive documentation and removing some annoying details (e.g. transaction management via thread-local — which is already on the roadmap), but we definitely recommend you give it a try in your project!

You May Also Like

Distributed scans with HBase

HBase is by design a columnar store, that is optimized for random reads. You just ask for a row using rowId as an identifier and you get your data instantaneously. Performing a scan on part or whole table is a completely different thing. First of all, it is sequential. Meaning it is rather slow, because it doesn't use all the RegionServers at the same time. It is implemented that way to realize the contract of Scan command - which has to return results sorted by key. So, how to do this efficiently?HBase is by design a columnar store, that is optimized for random reads. You just ask for a row using rowId as an identifier and you get your data instantaneously. Performing a scan on part or whole table is a completely different thing. First of all, it is sequential. Meaning it is rather slow, because it doesn't use all the RegionServers at the same time. It is implemented that way to realize the contract of Scan command - which has to return results sorted by key. So, how to do this efficiently?

Spock, Java and Maven

Few months ago I've came across Groovy - powerful language for JVM platform which combines the power of Java with abilities typical for scripting languages (dynamic typing, metaprogramming).

Together with Groovy I've discovered spock framework (https://code.google.com/p/spock/) - specification framework for Groovy (of course you can test Java classes too!). But spock is not only test/specification framework - it also contains powerful mocking tools.

Even though spock is dedicated for Groovy there is no problem with using it for Java classes tests. In this post I'm going to describe how to configure Maven project to build and run spock specifications together with traditional JUnit tests.


Firstly, we need to prepare pom.xml and add necessary dependencies and plugins.

Two obligatory libraries are:
<dependency>
<groupid>org.spockframework</groupId>
<artifactid>spock-core</artifactId>
<version>0.7-groovy-2.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupid>org.codehaus.groovy</groupId>
<artifactid>groovy-all</artifactId>
<version>${groovy.version}</version>
<scope>test</scope>
</dependency>
Where groovy.version is property defined in pom.xml for more convenient use and easy version change, just like this:
<properties>
<gmaven-plugin.version>1.4</gmaven-plugin.version>
<groovy.version>2.1.5</groovy.version>
</properties>

I've added property for gmaven-plugin version for the same reason ;)

Besides these two dependencies, we can use few additional ones providing extra functionality:
  • cglib - for class mocking
  • objenesis - enables mocking classes without default constructor
To add them to the project put these lines in <dependencies> section of pom.xml:
<dependency>
<groupid>cglib</groupId>
<artifactid>cglib-nodep</artifactId>
<version>3.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupid>org.objenesis</groupId>
<artifactid>objenesis</artifactId>
<version>1.3</version>
<scope>test</scope>
</dependency>

And that's all for dependencies section. Now we will focus on plugins necessary to compile Groovy classes. We need to add gmaven-plugin with gmaven-runtime-2.0 dependency in plugins section:
<plugin>
<groupid>org.codehaus.gmaven</groupId>
<artifactid>gmaven-plugin</artifactId>
<version>${gmaven-plugin.version}</version>
<configuration>
<providerselection>2.0</providerSelection>
</configuration>
<executions>
<execution>
<goals>
<goal>compile</goal>
<goal>testCompile</goal>
</goals>
</execution>
</executions>
<dependencies>
<dependency>
<groupid>org.codehaus.gmaven.runtime</groupId>
<artifactid>gmaven-runtime-2.0</artifactId>
<version>${gmaven-plugin.version}</version>
<exclusions>
<exclusion>
<groupid>org.codehaus.groovy</groupId>
<artifactid>groovy-all</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupid>org.codehaus.groovy</groupId>
<artifactid>groovy-all</artifactId>
<version>${groovy.version}</version>
</dependency>
</dependencies>
</plugin>

With these configuration we can use spock and write our first specifications. But there is one issue: default settings for maven-surefire plugin demand that test classes must end with "..Test" postfix, which is ok when we want to use such naming scheme for our spock tests. But if we want to name them like CommentSpec.groovy or whatever with "..Spec" ending (what in my opinion is much more readable) we need to make little change in surefire plugin configuration:
<plugin>
<groupid>org.apache.maven.plugins</groupId>
<artifactid>maven-surefire-plugin</artifactId>
<version>2.15</version>
<configuration>
<includes>
<include>**/*Test.java</include>
<include>**/*Spec.java</include>
</includes>
</configuration>
</plugin>

As you can see there is a little trick ;) We add include directive for standard Java JUnit test ending with "..Test" postfix, but there is also an entry for spock test ending with "..Spec". And there is a trick: we must write "**/*Spec.java", not "**/*Spec.groovy", otherwise Maven will not run spock tests (which is strange and I've spent some time to figure out why Maven can't run my specs).

Little update: instead of "*.java" postfix for both types of tests we can write "*.class" what is in my opinion more readable and clean:
<include>**/*Test.class</include>
<include>**/*Spec.class</include>
(thanks to Tomek Pęksa for pointing this out!)

With such configuration, we can write either traditional JUnit test and put them in src/test/java directory or groovy spock specifications and place them in src/test/groovy. And both will work together just fine :) In one of my next posts I'll write something about using spock and its mocking abilities in practice, so stay in tune.