Category: Spring

Hibernate with Kotlin – powered by Spring Boot

Hibernate with Kotlin – powered by Spring Boot

Hibernate with Kotlin – powered by Spring Boot

In this post, I’d like to demonstrate what you need to consider when using Hibernate with Kotlin. Hibernate is probably the most famous framework for object-relational mapping (ORM) on the JVM, which is used to persistently store Plain Old Java Objects (POJOs) in relational databases. It also implements the Java Persistence API, a specification that “describes the management of relational data” on the JVM.

Summary (TL;DR)

  • Put the kotlin-noarg compiler plugin on your build path, it will generate no-argument constructors for your Hibernate entities.
    • In Gradle, add the following to your buildscript dependencies: classpath("org.jetbrains.kotlin:kotlin-noarg:${kotlinVersion}")
    • Further examples can be found here
  • Enable the kotlin-jpa plugin, which works on top of kotlin-noarg by enabling the no-arg generation for Hibernate annotated classes
    • In Gradle, activate the plugin like this: apply plugin: "kotlin-jpa"
    • Further examples can be found here
  • Put the kotlin-allopen compiler plugin on your build path, and configure it to open classes with entity annotations as Hibernate should not be used with final classes
    • In Gradle, add the following to your buildscript dependencies: classpath "org.jetbrains.kotlin:kotlin-allopen:${versions.kotlin}" and add the following configuration:
    allOpen {
        annotation("javax.persistence.Entity")
        annotation("javax.persistence.MappedSuperclass")
        annotation("javax.persistence.Embeddable")
    } 
    
    • Further examples can be found here
  • Abstract your hashCode/equals implementations in an abstract base class and define entities as ordinary classes inheriting from the abstract base class
    • Do not use data classes to define your @Entity classes – JPA doesn’t work well with the generated equals/hashCode functions.

Hibernate Entity Type

The most important thing we need to do when integrating Hibernate into an application is defining the entity types we want to persist, i.e. defining the mappings between tables and classes. The Hibernate documentation describes an “Entity” as follows:

The entity type describes the mapping between the actual persistable domain model object and a database table row. To avoid any confusion with the annotation that marks a given entity type, the annotation will be further referred as @Entity.

Let’s see how valid entity classes need to look like.

Hibernate Requirements for Entity classes

Hibernate imposes certain requirements on a valid Entity type: An entity…

  • … must be annotated with the javax.persistence.Entity annotation (or be denoted as such in XML mapping, which we won’t consider)
  • … must have a public or protected (or package-private) no-argument constructor. It may define additional constructors as well
  • … should not be final. No methods or persistent instance variables of the entity class may be final (technically possible but not recommended)
  • … may extend non-entity classes as well as entity classes, and non-entity classes may extend entity classes. Both abstract and concrete classes can be entities
  • … may provide JavaBean-style properties. This is not a must, i.e. setters are not necessary
  • … must provide an identifier attribute (@Id annotation), recommended to use nullable, non-primitive, types
  • … needs to provide useful implementations for equals and hashCode (Why? find information here)

If we think about which kind of class in Kotlin best suits these requirements, one might say data classes did. As it turns out though, this is probably not the best solution as discussed in the following.

The equals/hashCode dilemma: Don’t use data classes as Hibernate entities

It seems to be a good idea to use data classes for defining our Hibernate entities: They basically just need a concise primary constructor with annotated parameters, provide neat things like hashCode, equals, copy, toString out of the box and may be immutable (actually they can’t be for Hibernate).

There’s a problem though: We need to be very careful with auto-generated equals/hashCode functions when working with Hibernate, especially because the entity identifier may be set after the object has been constructed. Actually, using auto-generated IDs means that our classes can never be immutable. Consider the following scenario:

  1. Create an object of your entity Person
  2. Put this object into a HashSet
  3. Persist object via Hibernate (this leads to a generated and updated Person::id and thus changes its hashCode)
  4. Test if the object still exists in the HashSet will yield false since the hash code changed

This dilemma could be fixed by using natural keys (aka business keys) instead, i.e. we’d need to find a combination of properties that clearly identify an entity. For a person, this could be their name and address, which still might be insufficient. We don’t have natural keys for every entity actually. Also, it’s a bit cumbersome to implement such behavior with data classes since we’d have to put the natural key parts into the primary constructor and everything else in the class body, the caller would have to set properties after construction. This does not feel right, so let’s not do it…

Hibernate Suggestion

What the Hibernate documentation suggests:

Although using a natural-id is best for equals and hashCode, sometimes you only have the entity identifier that provides a unique constraint. It’s possible to use the entity identifier for equality check, but it needs a workaround:
– you need to provide a constant value for hashCode so that the hash code value does not change before and after the entity is flushed.
– you need to compare the entity identifier equality only for non-transient entities.

They say that we can use the Hibernate-generated ID for equality checks as long as we provide a “constant value” for hashCode. This is because, reviewing the example scenario from earlier, the hash code should not change for an object once it’s been put into hash-based collections. Using a constant value for hashCode fixes this and still is a valid implementation according to its contract (taken from Oracle JavaDocs):

hashCode Contract

The general contract of hashCode is:
– Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application.
– If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.
– It is not required that if two objects are unequal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hash tables.

So this is all good although we need to take a closer look at the last sentence of this contract:

However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hash tables

hashCode Performance Implications

If we decide to yield constant values from hashCode for any object of a class, performance will suffer. You cannot expect hash collections to work as efficient as with properly distributed hash codes:

This implementation [HashMap] provides constant-time performance for the basic operations (get and put), assuming the hash function disperses the elements properly among the buckets.

If you can work around these performance implications, you should be fine to follow the described approach. For us, this isn’t considered problematic.

As a result, we want to let our entities’ equals be based on their identifier and provide a constant value for hashCode. Also, since data classes do not seem to be an adequate solution, we’ll be using ordinary, more flexible, classes.

Implementing Hibernate Entities with Kotlin

As a starter, it feels appropriate to provide a generic base class for our entities that defines an auto-generated identifier and, based on that, implements equals and the constant hashCode:


@MappedSuperclass abstract class AbstractJpaPersistable<T : Serializable> { companion object { private val serialVersionUID = -5554308939380869754L } @Id @GeneratedValue private var id: T? = null override fun getId(): T? { return id } override fun equals(other: Any?): Boolean { other ?: return false if (this === other) return true if (javaClass != ProxyUtils.getUserClass(other)) return false other as AbstractJpaPersistable<*> return if (null == this.getId()) false else this.getId() == other.getId() } override fun hashCode(): Int { return 31 } override fun toString() = "Entity of type ${this.javaClass.name} with id: $id" }

The class AbstractJpaPersistable is pretty straightforward: It defines a generic nullable @Id property, which is going to be auto-generated by Hibernate. The equals and hashCode look like discussed earlier. Now we can create our entities based on that class:

@Entity
class Person(
    val name: String,
    @OneToOne(cascade = [(CascadeType.ALL)], orphanRemoval = true, fetch = FetchType.EAGER)
    val address: Address
) : AbstractJpaPersistable<Long>()

@Entity
class Address(
    val street: String,
    val zipCode: String,
    val city: String
) : AbstractJpaPersistable<Long>()

We can see two rather simple entities: A Person which has an associated Address. Both @Entity classes extend AbstractJpaPersistable<Long> and therefore rely on an auto-generated id of type Long.

Reviewing the entity requirements

As depicted earlier, we have a few requirements for entities that need to be considered. Let’s review what the approach from above already takes care of:

The Entity…

  • … must be annotated with the javax.persistence.Entity annotation (or be denoted as such in XML mapping, which we won’t consider) ✔️
  • … must have a public or protected (or package-private) no-argument constructor. It may define additional constructors as well ❌
  • … should not be final. No methods or persistent instance variables of the entity class may be final (technically possible but not recommended) ❌
  • … may extend non-entity classes as well as entity classes, and non-entity classes may extend entity classes. Both abstract and concrete classes can be entities ✔️
  • … may provide JavaBean-style properties. This is not a must, i.e. setters are not necessary ✔️ (We accept to not have setters)
  • … must provide an identifier attribute (@Id annotation), recommended to use nullable, non-primitive, types ✔️
  • … needs to provide useful implementations for equals and hashCode ✔️

We still have two things to fix:
1. Kotlin classes are final by default, which is good practice in most cases but Hibernate does not really like that. Since it makes use of proxies that allow e.g. lazy-loading of entities, classes should not be final if possible.
2. We did not provide a no-argument constructor so far.

The following will take care of both problems.

Writing a sample application

Setup

Now that we know how to abstract Hibernate entities properly, let’s write a sample application and see if there are more things to consider. We’ll use a Spring Boot base for our application which can easily be generated via start.spring.io:

start.spring.io
start.spring.io

(If you like to find out more about Spring and its fantastic Kotlin support, I encourage you to read this blog post as well.)

Fixing remaining Entity requirements

As discussed earlier, Hibernate expects a no-argument constructor defined for its entities. Since we don’t want to provide one at compile time, we use a compiler plugin by JetBrains called kotlin-noarg, which “generates an additional zero-argument constructor for classes with a specific annotation. The generated constructor is synthetic so it can’t be directly called from Java or Kotlin, but it can be called using reflection.”

In addition, we need to tell the tool which annotations it should apply the no-arg constructor rule on. This can be done manually or by adding the plugin kotlin-jpa to our build, which is “wrapped on top of no-arg. The plugin specifies @Entity, @Embeddable and @MappedSuperclass no-arg annotations automatically.”

Also, taking care of the final classes problem, we configure the kotlin-allopen plugin to remove the final modifier from all compiled entity classes.

The Gradle build file

Altogether, the build script looks like this (Gradle Groovy DSL):

buildscript {
    ext {
        kotlinVersion = '1.2.60'
        springBootVersion = '2.0.4.RELEASE'
        h2 = '1.4.196'
    }
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
        classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:${kotlinVersion}")
        classpath("org.jetbrains.kotlin:kotlin-allopen:${kotlinVersion}")
        classpath("org.jetbrains.kotlin:kotlin-noarg:${kotlinVersion}")
    }
}

apply plugin: 'kotlin'
apply plugin: 'kotlin-spring'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'
apply plugin: "kotlin-jpa"

group = 'com.kotlinexpertise'
version = '0.0.1-SNAPSHOT'

sourceCompatibility = 1.8

repositories {
    mavenCentral()
}

allOpen {
    annotation("javax.persistence.Entity")
    annotation("javax.persistence.MappedSuperclass")
    annotation("javax.persistence.Embeddable")
}

dependencies {
    compile('org.springframework.boot:spring-boot-starter-data-jpa')
    compile('org.springframework.boot:spring-boot-starter-web')
    compile("org.jetbrains.kotlin:kotlin-stdlib-jdk8")
    compile("org.jetbrains.kotlin:kotlin-reflect")
    // Database Drivers
    compile("com.h2database:h2:$h2")

    //Jackson Kotlin
    compile('com.fasterxml.jackson.module:jackson-module-kotlin')

    //Junit 5
    testCompile('org.springframework.boot:spring-boot-starter-test') {
        exclude module: 'junit'
    }
    testImplementation('org.junit.jupiter:junit-jupiter-api')
    testRuntimeOnly('org.junit.jupiter:junit-jupiter-engine')

    testCompile('org.springframework.boot:spring-boot-starter-test')

}

We can also see some additional dependencies for Jackson, Junit5 (Jupiter) and an in-memory H2 database.

This results in a neat setup with valid Hibernate entities:

The Entity…

  • … must be annotated with the javax.persistence.Entity annotation (or be denoted as such in XML mapping, which we won’t consider) ✔️
  • … must have a public or protected (or package-private) no-argument constructor. It may define additional constructors as well ✔️
  • … should not be final. No methods or persistent instance variables of the entity class may be final (technically possible but not recommended) ✔️
  • … may extend non-entity classes as well as entity classes, and non-entity classes may extend entity classes. Both abstract and concrete classes can be entities ✔️
  • … may provide JavaBean-style properties. This is not a must, i.e. setters are not necessary ✔️ (We accept not to have setters)
  • … must provide an identifier attribute (@Id annotation), recommended to use nullable, non-primitive, types ✔️
  • … needs to provide useful implementations for equals and hashCode ✔️

A simple repository

Thanks to Spring, the implementation for a repository that exposes Person entities is quite easy:

interface PersonRepository : JpaRepository<Person, Long> {
    fun getByAddressStreet(street: String): Person?
}

The interface org.springframework.data.jpa.repository.JpaRepository defines common CRUD operations and we add custom ones by extending the interface with PersonRepository. You can find out more about this mechanism here. As you might guess, the implementation of such an abstract repository definition happens via Spring.
You could now go on and inject this repository into controllers and expose a CRUD API to users. For simplicity, observe the following test case:

@ExtendWith(SpringExtension::class)
@SpringBootTest
class HibernateDemoApplicationTests(@Autowired val repo: PersonRepository) {

    @Test
    fun `basic entity checks`() {
        val p = Person("Paul", Address("HelloStreet", "A-55", "Paris"))
        val hashCodeBefore = p.hashCode()
        val personSet = hashSetOf(p)
        repo.save(p)
        val hashCodeAfter = p.hashCode()
        assertThat(repo.findAll()).hasSize(1)
        assertThat(personSet).contains(p)
        assertThat(hashCodeAfter).isEqualTo(hashCodeBefore)
    }
}

This test runs on JUnit 5, which allows constructor injection for certain objects. The used SpringExtension adds support for autowired dependencies and, as a result, we can inject the PersonRepository into the test class.
In the test case itself, we create a sample Person object, persist it by using the repository and then verify that it can be found via findAll. Assertions are based on org.assertj.
In addition, the test verifies that the hashCode for a Person does not change after it got persisted through Hibernate and that a HashSet works properly with these entities.

Further Hibernate Topics

In this article, we focused mainly on defining Hibernate entity classes since this task is probably the most vital one to do. We saw that a few constraints need to be fulfilled and that compiler plugins help us with integrating Hibernate with Kotlin. All of the demonstrated stuff is just a tiny set of Hibernate. Thanks to Spring though, many things like querying and transaction handling can easily be abstracted, which we made use of here. If you have doubts, I suggest to read “How Hibernate Almost Ruined my Career” very carefully – Hibernate can cause many headaches obviously ;-).

The source code can be found in my hibernateOnKotlin repository on GitHub.

Please don’t hesitate to reach out if you use different best practices in your applications.
Also, if you like, have a look at my Twitter account and other Kotlin related posts on this page and follow if you’re interested in more Kotlin stuff 🙂

Thanks a lot.

Simon is a software engineer based in Germany with 7 years of experience writing code for the JVM and also with JavaScript. He’s very passionate about learning new things as often as possible and a self-appointed Kotlin enthusiast.

Please follow and like this Blog 🙂
Spring WebFlux with Kotlin – Reactive Web

Spring WebFlux with Kotlin – Reactive Web

Spring 5.0 – even fancier

In this article I will show how Spring and Kotlin can be used together. If you’re not familiar with my recent articles, have a look at the other Kotlin related posts here. Besides Kotlin, I’ve always been interested in working with Spring ever since I started with Java back in 2011. I still like the framework although it’s getting bigger and bigger and you often don’t quite know which feature to choose amongst all the alternatives. As the framework itself is growing, the documentation, which is one of best you’ll ever get to see, also is.

The thing I like most about Spring is that you can focus on your business logic from day one and don’t have much technical, infrastructural stuff to set up before kicking off. Spring does that by encapsulating a lot of boilerplate that’s necessary for certain tasks and provides simple annotations we can apply in order to make use of these features. One of the most famous modules certainly is Spring Web MVC, which is widely used whenever it comes to web services on the JVM.

Reactive Programming – The non-blocking way

You might have noticed that Reactive Programming is getting more attention recently. There are many frameworks emerging that want to encourage this style of programming, namely RxJava, Vert.X or Akka for example. If you’ve never come across these, you can read my post on Kotlin with Vert.X as a first step.

Spring reactive

What does this have to do with Spring though? Well, of course, there’s yet another library for building reactive systems, which in fact is powered by Spring: [Project Reactor] https://projectreactor.io). Reactor is used in the current Spring Release 5.0, available since September 2017, which introduces a reactive web framework called WebFlux.
This fact on its own is a good reason for me to dive into it as it sounds fairly fantastic knowing Web MVC as Spring’s outstanding module already. But, there’s yet another great reason to take this expansion into account: Spring is greatly supporting Kotlin and even introduced Kotlin dedicated features with the recent major release 🙂 This was achieved by making use of extension functions in order to extend existing APIs and also by introducing Kotlin DSLs, a feature you can read about in my post on creating a DSL with Kotlin. One of these new DSLs goes hand in hand with Spring WebFlux: A functional DSL for describing the WebFlux-backed web service. This, in fact, is what I am going to present to you in a very short example up next…

WebFlux and Kotlin in Action

Let’s have a look at a very basic application using Spring WebFlux in a Kotlin application. The initial setup can easily be downloaded as a SpringBoot application from Spring Initializr, if you choose Kotlin as the programming language and also enable the “Reactive Web” dependency, which is available since SpringBoot 2.0.0.

spring boot initilizr

As soon as we’ve imported this project into our IDE, we can start with creating a reactive web service. For the sake of brevity, I chose a very simple, not very useful, example: An internally managed repository of simple Strings that is populated through the web interface and also is searchable from it. Thanks to Kotlin and also Spring, there’s not much code that has to be written:

Repo and Handler

@Component
class ReactiveHandler(val repo: StringRepo) {
    fun getText(search: String): Mono<String> =
        repo.get(search).toMono().map { "Result: $it!" }
    fun addText(text: String): Mono<String> =
        repo.add(text).toMono().map { "Result: $it!" }
    fun getAllTexts(): Flux<String> =
        repo.getAll().toFlux().map { "Result: $it" }
}

@Component
class StringRepo {
    private val entities = mutableListOf<String>()
    fun add(s: String) = entities.add(s)
    fun get(s: String) = entities.find { it == s } ?: "not found!"
    fun getAll() = listOf(entities)
}

We simply create a repository that maintains a list of Strings and another class ReactiveHandler, which is responsible for delegating to the repository and providing “reactive types” defined in Reactor. These are mandatory for WebFlux: Flux and Mono (Read about them here). Regardless of their intention, have a look at how they are created: toMono() and toFlux() are examples of extension functions added in Spring 5.0, a feature dedicated to Kotlin. The much more interesting part though is where the web routing is defined. This part in particular is where the already mentioned functional DSL comes into play. Let’s observe how it works.

Functional WebFlux DSL.

@Configuration
class RoutingConfiguration {

    @Bean
    fun routerFunction(handler: ReactiveHandler): RouterFunction<ServerResponse> = router {
        ("/reactive").nest {
            val searchPathName = "search"
            val savePathName = "save"
            GET("/{$searchPathName}") { req ->
                val pathVar = req.pathVariable(searchPathName)
                ServerResponse.ok().body(
                        handler.getText(pathVar)
                )
            }
            GET("/") {
                ServerResponse.ok().body(handler.getAllTexts())
            }
            PUT("/{$savePathName}") { req ->
                val pathVar = req.pathVariable(savePathName)
                ServerResponse.ok().body(
                        handler.addText(pathVar)
                )
            }
        }
    }
}

The router function is the entry point of the new DSL, which can be inspected on GitHub. The shown solution is just one out of many since the DSL provides more ways you can choose from. With my definition, the server starts a web service under “/reactive” and accepts two GET and one PUT request, each of which is delegated to the previously shown ReactiveHandler (see method parameter) before the results are put into a ServerResponse. Of course, you’d have to handle errors in a real-world scenario and “ok” wouldn’t be the only response.

Benefit

If you ask me, this approach is very clean structured and even provides the opportunity of using any Kotlin code for defining variables, loops, conditions, whatsoever inside the actual DSL code. Given that, you have a very powerful tool that can be utilized in a very natural programmatic way.

If your like to check this out, the code is available in this GitHub repository.

Wrap-up and Perspective

I’ve presented a small project that’s making use of Spring 5.0 and its new module WebFlux in combination with Kotlin. I think, the fact, that Spring officially uses and supports Kotlin is a very important one, I’d like to emphasize once again.

Kotlin – It’s not only Android!

We all know that Kotlin made its way into Android, which was possible because Google announced the official support a few months ago. On the server-side though, people and especially companies hesitate when it comes to Kotlin. They tend to have doubts as to whether Kotlin’s really mature enough already.
When you ask me, there’s no good reason for hesitation. Many projects use Kotlin already, frameworks support Kotlin and even extend their libraries with dedicated Kotlin features. Spring, as one of the most common Java frameworks, seems to think the same as they quickly adopted Kotlin as an alternative to Java and Groovy for SpringBoot applications. The most recent developments, which are part of Spring 5.0, are the next step, some of which we’ve observed in this little article. If you’re, same as me, interested in spreading Kotlin as an alternative to Java, talk about it and tell your colleagues about Spring’s support and what’s actually
happening 😉

Special Thanks

As you can read in this article, Spring’s introducing quite a few Kotlin features. There’s one guy, Sébastien Deleuze, who’s highly responsible for this development in the Spring Framework. He has also been a guest on talkingkotlin
already. It’s really great to have such influencers in the Kotlin community, many thanks! Keep up the great work.

If you like to have a look at my examples, the code is available here:
Git. Feel free to give any feedback, I’m always happy to help. Also, if you like, have a look at my Twitter account and follow if you’re interested in more Kotlin stuff 🙂 Thanks a lot.

Simon is a software engineer based in Germany with 7 years of experience writing code for the JVM and also with JavaScript. He’s very passionate about learning new things as often as possible and a self-appointed Kotlin enthusiast.

Please follow and like this Blog 🙂