<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Łukasz Pięta on Medium]]></title>
        <description><![CDATA[Stories by Łukasz Pięta on Medium]]></description>
        <link>https://medium.com/@pientaa?source=rss-7ec306a61a06------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*bEdJzviQl_laptMV1vEhYg.jpeg</url>
            <title>Stories by Łukasz Pięta on Medium</title>
            <link>https://medium.com/@pientaa?source=rss-7ec306a61a06------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 06:16:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@pientaa/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com" rel="hub"/>
        <item>
            <title><![CDATA[Null Safety]]></title>
            <link>https://medium.com/kotlin-academy/null-safety-bb20b0cbf1a4?source=rss-7ec306a61a06------2</link>
            <guid isPermaLink="false">https://medium.com/p/bb20b0cbf1a4</guid>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[null-safety]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Łukasz Pięta]]></dc:creator>
            <pubDate>Sat, 03 Aug 2024 15:09:15 GMT</pubDate>
            <atom:updated>2024-08-10T14:40:56.042Z</atom:updated>
            <content:encoded><![CDATA[<h4>The reason why Java will never catch up to Kotlin</h4><p>There are multiple reasons to choose Kotlin over Java as your programming language. Of course, as with many technical decisions, “it depends”, doesn’t it? Moreover, everyone has their own opinion, and it wouldn’t be a surprise if you don’t share mine.</p><p>However, if you asked me — Kotlin is better than Java 😁. Even though the latest Java releases are truly promising, it still lags significantly behind Kotlin. Perhaps one of the most significant and challenging gaps to bridge is the structured null safety Kotlin guarantees at compile time. Is that really such a big deal? — you might ask, let’s figure out!</p><h3>Null Safety Through the Eyes of AI</h3><p>What is “Null Safety” in general? Below, you can see an image generated by OpenAI’s DALL·E model, which was asked to embody “Kotlin null safety.”</p><figure><img alt="“Kotlin null safety” image created using OpenAI’s DALL·E." src="https://cdn-images-1.medium.com/max/1024/0*wUMzn-K3NpRPRMK6" /><figcaption>“Kotlin null safety” image created using OpenAI’s DALL·E.</figcaption></figure><p>In the center of the image, we can see a cosmic portal, which might be interpreted as a gateway of knowledge. The whole scenery looks very scientific and futuristic. Many mathematical symbols surround the portal, creating the impression of floating energy accumulating there. Beneath the portal, there is a circular platform with an amphitheater-like structure, encircled by towering pillar-like buildings that hint at an advanced civilization.</p><p>Based on the above image, we can imagine what Kotlin null safety is. It can be thought of as a protective gateway that prevents NPEs (Null Pointer Exceptions). The well-organized structures surrounding the platform on which the portal is placed suggest the structured approach Kotlin uses to handle nullability in a systematic and safe manner.</p><p>However, I don’t want to convince you to use Kotlin just because of an image generated by AI. That would be absurd! Assuming that Java is our reference point, let’s take a look at its approach to null safety (is there even such an approach in Java? Just kidding… but am I? 😂). But to get there, let’s take a step back and answer the question: is “null” (to be precise: <a href="https://en.wikipedia.org/wiki/Null_pointer">Null Reference</a>) such a big problem at all?</p><h3>“The billion dollar mistake”</h3><p>It all started back in 1965, when <a href="https://en.wikipedia.org/wiki/Tony_Hoare">Tony Hoare</a> invented the null reference as part of the <a href="https://en.wikipedia.org/wiki/ALGOL_W">ALGOL W</a> language. The problem he intended to solve with his invention was to indicate the absence of an object in a simple and memory-efficient fashion. There was no standardized way to do it yet, and any additional data structures or special cases for the absence of value were not optimal in terms of efficiency in the resource-constrained environments of early computing.</p><p>And after over four decades <a href="https://www.infoq.com/presentations/Null-References-The-Billion-Dollar-Mistake-Tony-Hoare/">he states</a>:</p><blockquote>I call it my billion-dollar mistake. It was the invention of the null reference in 1965. At that time, I was designing the first comprehensive type system for references in an object oriented language (ALGOL W). My goal was to ensure that all use of references should be absolutely safe, with checking performed automatically by the compiler. But I couldn’t resist the temptation to put in a null reference, simply because it was so easy to implement. This has led to innumerable errors, vulnerabilities, and system crashes, which have probably caused a billion dollars of pain and damage in the last forty years.</blockquote><p>But wait, is really “null” such a big deal? Why does it cause so much pain and damage if we can simply perform a null check before we use a variable?</p><pre>if(sth != null) { ... }</pre><p>Some says it’s ugly, but it doesn’t bother me. The problem is not the code itself, but the concept in general. There are multiple issues caused by null pointers:</p><ul><li><strong>Proliferation of null checks </strong>— You can’t simply trust that what you operate on is a non-null value. Of course, you can work out with your team some architectural design which helps to keep all the null checks in one of the top layers, so you don’t need to bother in the inner layers about them. But it’s still hidden, not presented straight forward to the developer through the type system.</li><li><strong>Error-prone </strong>— Forgetting a null check (especially when refactoring) can lead to NPEs, which are difficult to trace and often cause application crashes.</li><li><strong>Default and Unexpected States </strong>— Using null to represent the absence of a value can be ambiguous. It’s not clear if it’s an uninitialized variable, an absent value, or an error condition.</li><li><strong>Encapsulation Violations </strong>— Properly encapsulated objects should manage their own state, but it’s the client using the object who is responsible for performing null checks.</li><li><strong>Impact on Functional Programming </strong>— In languages supporting functional programming paradigms, nulls can complicate the use of functions and higher-order functions. Handling nulls can break the chain of function calls and make composition difficult.</li></ul><h3>How to minimize the risk of NPEs in Java?</h3><p>Assuming you don’t have a null safety feature in the language you use, how can you minimize the risk of NPEs? Here are several rules to follow that can help you do that:</p><h4><strong>Consider using empty collection instead of null</strong></h4><p>In many business cases, null is identical to an empty list or an array, so when it makes no difference from a business perspective, it can be simply replaced. However, keep in mind that it’s not always the same thing. For example, filtering by request parameters is fundamentally different when you don’t want to filter by a parameter versus when your filtering parameter is an empty list.</p><h4>Use null-safe object wrappers</h4><p>Handling an Object null-case scenario might be much harder than replacing null with an empty list when dealing with collections, especially if there is no nullable type in the type system of your programming language. However, there are some ways to minimize the risk of NPEs, even without built-in null safety in your programming language.</p><ul><li><a href="https://en.wikipedia.org/wiki/Null_object_pattern">Null Object Pattern</a>: An approach where there is a “null implementation” of an object.</li></ul><pre>// Example of Null Object Pattern Implementation<br>public class Product {<br>    private int productId;<br>    private String productName;<br>    private double price;<br><br>    public String getProductName() {<br>       // ...<br>    }<br>    <br>    public void setProductName(String productName) {<br>       // ...<br>    }<br>    <br>    public double getPrice() {<br>       // ...<br>    }<br>    <br>    public void setPrice(double price) {<br>       // ...<br>    }<br>}<br><br>public class EmptyProduct extends Product {<br><br>    public int getProductId() {<br>       return -1;<br>    }<br><br>    public String getProductName() {<br>       return &quot;&quot;;<br>    }<br>    <br>    public double getPrice() {<br>       return 0.0;<br>    }<br>}<br><br>public Product getProductEntry() {<br>   Product result = db.getProduct();<br>   if(result == null) {<br>       return new EmptyProduct();<br>   } else {<br>       return result;<br>    }<br>}</pre><ul><li>Optional wrapper (<a href="https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html">Java implementation</a>): Probably the most common approach, where we have a wrapper on a generic type with access to a rich API with many useful functions.</li></ul><pre>// Example of Optional wrapper usage<br>public Optional&lt;Product&gt; getProductEntry() {<br>    return Optional.ofNullable(db.getProduct());<br>}<br><br>Optional&lt;Product&gt; optionalProduct = getProductEntry();<br><br>if (optionalProduct.isPresent()) {<br>    Product product = optionalProduct.get();<br>    // Handle the product<br>} else {<br>    // Handle the case when product is not found<br>}</pre><p>And this is actually what people refer to as “null safety in Java” — as you can see below, there is no such thing at all:</p><pre>// This will compile<br>Optional&lt;Product&gt; optionalProduct = null;<br><br>// This will throw NPE<br>optionalProduct.isPresent();</pre><p>Don’t trust people who say there is null safety in Java! As you can see, there is not.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*437mXhts922mx5rmaiwP3w.png" /></figure><h4>Use @Nullable annotation</h4><p>However, there is one more tool that can help you avoid NPEs in Java: the @Nullable annotation. It can be used to mark a method parameter, return value, or field as potentially null. Although it doesn&#39;t guarantee null safety at compile time, it relies on external tools (like IDEs or static analysis tools) to catch potential nullability issues.</p><p>To sum up, yes, you can minimize the risk of NPEs in Java, but your hands are tied, and there is no other way than maintaining strict discipline within the team and using workarounds such as Optional&lt;T&gt; and the null object pattern, which add complexity to your code. This still doesn’t guarantee that your system is safe enough, and there won’t be some NPEs propagated to the heart of your application, where you expect it to be the least likely to occur.</p><figure><img alt="“Java’s lack of inherent null safety” image created using OpenAI’s DALL·E." src="https://cdn-images-1.medium.com/max/1024/0*mQGwgCX2gUxdIzVR" /><figcaption>“Java’s lack of inherent null safety” image created using OpenAI’s DALL·E.</figcaption></figure><p>Java has many flaws, but the lack of null safety is, in my opinion, the biggest one and probably the hardest to address due to the need for backward compatibility in upcoming releases. That’s why Kotlin did it much better. Since it’s very young, it was able to learn from Java’s (and other languages’) mistakes, making it such a terrific programming language.</p><h3>Kotlin Null Safety</h3><h4>Nullable Types</h4><p>First of all, Kotlin’s type system consists of nullable and non-nullable types. Basically, a nullable type can be easily created from a non-nullable type by adding a question mark to the end of the type name, e.g., the nullable type of String is String?. When it comes to inheritance, a non-nullable type is always a subtype of a nullable one.</p><pre>var nonNullableString: String = &quot;Some value&quot;<br>var nullableString: String? = &quot;Some other value&quot;<br><br>nullableString = nonNullableString // it compiles<br>nullableString = null // it compiles<br><br>nonNullableString = nullableString // it doesn&#39;t compile<br>nonNullableString = null // it doesn&#39;t compile</pre><p>As seen above, we can’t assign a null value to a non-nullable type, because it results in a compilation error. This is, in my opinion, the biggest advantage of Kotlin’s approach to null safety — compilation-time assurance of null-safe correctness.</p><p>While Optional&lt;T&gt; gives a very rich API with plenty of methods, Kotlin’s null-safety is extremely simple and minimalistic. Therefore it’s much easier to use in day-to-day work, because it simply does not put any boilerplate code and does not disrupt understanding of the business logic in the actual code.</p><h4>Safe call operator</h4><p>One of the key tools that Kotlin implements for null safety is the safe call operator ?., which let us call a property or a method of nullable variable in a safe way. This means that the program will proceed to the right side of the safe call operator only if the left side is not null; otherwise, a null value will be propagated through the call without throwing any exception. This behavior is intentional, as it allows nullable types to handle cases with null values gracefully.</p><pre>data class Product(<br>    val productId: Int,<br>    val productName: String?,<br>    val price: Double<br>)<br><br>fun productNameToUpperCase(product: Product): String? {<br>    return product.productName?.toUpperCase() <br>} </pre><h4>Elvis Operator</h4><p>Another inherent element of Kotlin’s null safety is the Elvis operator ?:, which allows you to provide a default value if an expression evaluates to null.</p><pre>fun productNameToUpperCase(product: Product): String {<br>    return product.productName?.toUpperCase() ?: &quot;Name unknown&quot;<br>}</pre><p>The Elvis operator can also be used if you want to throw an exception when a value is null.</p><pre>fun productNameToUpperCase(product: Product): String {<br>    return product.productName?.toUpperCase() ?: throw IllegalStateException()<br>}</pre><h4>Non-null assertion</h4><p>The non-null assertion !! also seems very tempting, but it should be used very cautiously because if you apply it in a place where a null value occurs, a NPE will be thrown immediately. A better strategy is to use your own custom exceptions for easier troubleshooting and debugging.</p><pre>fun productNameToUpperCase(product: Product): String {<br>    return product.productName?.toUpperCase()!!<br>}</pre><p>My personal advice is to avoid using the non-null assertion, as it reintroduces the risk of unexpected NPEs. The most suitable place for !! is probably in a test package, where there might be a need to force the compiler to ignore the nullability of some already initialized properties.</p><h4>Safe cast operator</h4><p>On the other hand, the safe cast operator as? can be very useful for soft casting and prevents unexpected exceptions from occurring when casting types.</p><pre>data class Product(<br>    val productId: Int,<br>    val productName: String?,<br>    val price: Double<br>)<br><br>data class DiscountedProduct(<br>    val productId: Int,<br>    val productName: String?,<br>    val price: Double,<br>    val discountPercentage: Double<br>) : Product(productId, productName, price)<br><br>fun processProduct(product: Product) {<br>    val discountedProduct = product as? DiscountedProduct<br>    discountedProduct?.let {<br>        // Handle discounted product<br>    } ?: run {<br>        // Handle regular product<br>    }<br>}</pre><h4>Late-Initialized Properties</h4><p>Another cool feature in Kotlin, which might be useful when dealing with null safety, is the lateinit keyword for late-initialized properties. It can be used for properties that will be initialized after the object is created, but we don&#39;t want them to be nullable.</p><pre>class ProductManager {<br>    private lateinit var product: Product<br><br>    fun initializeProduct() {<br>        product = Product(1, &quot;Sample Product&quot;, 19.99)<br>    }<br><br>    fun printProductName() {<br>        if (::product.isInitialized) {<br>            println(product.productName)<br>        } else {<br>            println(&quot;Product is not initialized&quot;)<br>        }<br>    }<br>}</pre><p>All these features are just tools, so they can be used either in a good or a wrong manner. You might not use them all at once, but feel free to mix them according to your needs. In the end, let me share some tips from my experience as a Kotlin Developer.</p><h4>As Nullable as Necessary, but No More</h4><p>Having nullable and non-nullable types creates a very flexible environment to design either a perfect API or a poor one. In general, Kotlin developers can be divided into two groups: 1. those who insist on making nothing nullable at all (because no one should accept a nullable type in business logic!), and 2. those who make everything nullable by default (because it’s much easier when starting to write code). The bad news is that both approaches are fundamentally wrong. There is a very good reason for both types — nullable and non-nullable — to exist, and each should be used in different cases.</p><p>Here are my rules of thumb:</p><ul><li>Make sure you don’t lose business value due to too many properties being nullable— maybe your aggregate should be divided into smaller ones if so many things can be empty (null) at the same time?</li><li>Returning a null value from a function responsible for looking for some data is not a bad idea — it’s much better to expect null value and handle it properly than to perform a try-catch on a method that is going to throw a NoSuchElementException.</li><li>Don’t hinder yourself in debugging by creating nested nullable data types — it’s sometimes very hard to figure out what actually was null in such a navigation chain: person?.account?.address?.city.</li></ul><h4>Talk like a Kotlin native</h4><p>Notice the Kotlin naming conventions. Take a look at the following commonly used functions from the Kotlin standard library:</p><pre>package kotlin.collections<br><br>public interface List&lt;out E&gt; : Collection&lt;E&gt; {<br>   public operator fun get(index: Int): E<br>   //...<br>}<br><br>public fun &lt;T&gt; List&lt;T&gt;.getOrNull(index: Int): T?</pre><p>As you can see, it’s a good practice to name your function in such way which already suggests what type (nullable or not) should be expected. Even though we can check the return type, having it clarified in the function name makes the code more readable. However, while it appears to be for readability’s sake, it actually stems from a compiler limitation: we can’t have more than one function with the same signature.</p><pre>data class Person(private val id: String)<br><br>fun findBy(id: String): Person {<br>    return Person(id)<br>}<br><br>fun findBy(id: String): Person? {<br>    return null<br>}</pre><p>The code above causes following compilation error:</p><pre>Conflicting overloads: public fun findBy(id: String): Person defined in root package in file Foo.kt, public fun findBy(id: String): Person? defined in root package in file Foo.kt</pre><p>Finally, if you wonder what the Kotlin coding conventions are, either take inspiration from the Kotlin standard library or any other Kotlin library commonly used among Kotlin developers, or take a look at the official Kotlin documentation, where you can find the <a href="https://kotlinlang.org/docs/coding-conventions.html">document with coding conventions</a>.</p><h4>Never trust Java clients!</h4><p>One of the most frequently crashing parts of a Kotlin application, in my experience, is when you integrate with a Java client (e.g., Hibernate, which seems to frustrate many people, although it’s really not that bad — <a href="https://medium.com/better-programming/hibernate-is-not-so-evil-84ca72b959c3">check out my article about it</a>).</p><p>Consider the following Java code:</p><pre>// File: JavaClass.java<br>public class JavaClass {<br>    public String getNullableString() {<br>        return null;<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cAO69hOOxRAq7rRK5IBNVA.png" /></figure><p>When we try to invoke it in Kotlin, we will end up with the type String!, which should catch your attention, because the type is signalling that something might be wrong. Types of Java declarations are called <a href="https://kotlinlang.org/docs/java-interop.html#null-safety-and-platform-types">platform types</a>, and they are treated in a specific way in Kotlin.</p><pre>val foo: String? = JavaClass().nullableString // allowed<br>println(foo?.length) // This works fine<br><br>val bar: String = JavaClass().nullableString // allowed<br>println(bar.length) // This throws NPE</pre><p>As you can see, when integrating with a Java library, we need to consider null cases that might occur in Java code due to the lack of null safety. When it comes to handling platform types, you always have two options:</p><ol><li>Use a nullable type and handle the null case yourself.</li><li>Use a non-nullable type and expect an assertion upon assignment, so an NPE will be thrown if the Java client returns a null value.</li></ol><p>Notice that if a Java client used @Nullable annotation compatible with your IDE , you would see String? instead of String!.</p><pre>import org.jetbrains.annotations.Nullable;<br><br>// File: main.JavaClass.java<br>public class JavaClass {<br>    @Nullable<br>    public String getNullableString() {<br>        return null;<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8xRF-Xaa2PPcYEf2gyoP2A.png" /></figure><h3>Still not convinced to switch from Java to Kotlin?</h3><p>Even if you were on the Java side in this conflict between Java and Kotlin at the beginning of my article, I hope you’ve started thinking about Kotlin in a much more positive way. If null safety hasn’t convinced you enough and you’re curious about Kotlin’s capabilities, stay tuned, because I’m going to publish more Kotlin content in the near future.</p><p>However, there is one more thing I’d like to mention regarding the choice between Java and Kotlin. Respected companies have proven through their experiences that, in general, switching from Java to Kotlin:</p><ul><li>Increases productivity: 70% of developers whose primary language is Kotlin say that Kotlin makes them more productive.</li><li>Produces satisfaction among programmers who participated in the transition: 87% of Google server-side Kotlin developers are “very satisfied” with Kotlin.</li><li>Makes your applications more stable: Google observed a 20% lower likelihood of Android applications crashing.</li><li>Doesn’t result in any productivity degradation if some parts of the system are left in good old Java (Google observation).</li></ul><p>Link to the source of statistics: <a href="https://www.youtube.com/watch?v=o14wGByBRAQ">Google’s Journey from Java to Kotlin for Server Side Programming, Devoxx</a>.</p><p>Thanks for reading my article. I hope you enjoyed it! If you have any thoughts on it, please let me know; I’m happy to discuss it further.</p><p>I’d like to thank <a href="https://medium.com/u/52b77f020913?source=post_page-----84ca72b959c3--------------------------------">Adrian Glapiński</a> and <a href="https://medium.com/u/dddcafb2a42e?source=post_page-----84ca72b959c3--------------------------------">Paweł Dereziński</a> for being very helpful in reviewing my article. I appreciate it a lot!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bb20b0cbf1a4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/kotlin-academy/null-safety-bb20b0cbf1a4">Null Safety</a> was originally published in <a href="https://medium.com/kotlin-academy">kt.academy</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hibernate is not so evil]]></title>
            <link>https://medium.com/better-programming/hibernate-is-not-so-evil-84ca72b959c3?source=rss-7ec306a61a06------2</link>
            <guid isPermaLink="false">https://medium.com/p/84ca72b959c3</guid>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Łukasz Pięta]]></dc:creator>
            <pubDate>Fri, 18 Aug 2023 05:00:10 GMT</pubDate>
            <atom:updated>2023-08-19T17:14:17.554Z</atom:updated>
            <content:encoded><![CDATA[<h4>You just don’t know it well enough</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*btYJHKn8vEcLsG9RTL--1w.png" /><figcaption>Photo from my presentation about Hibernate at <a href="https://warszawskiedniinformatyki.pl/en/">Warsaw IT Days</a></figcaption></figure><p>A few years ago, when I was a Junior Backend Developer, I was really frustrated at Hibernate. Every time I made any change in the persistence layer designed by my older colleagues, I had serious problems with JPA. I thought that maybe Hibernate was some kind of an old crappy tool nobody wants to use anymore. Especially, when I saw the alternatives — lightweight, small ORM frameworks like <a href="https://github.com/JetBrains/Exposed">Exposed</a>.</p><p>However, after many years of using JPA, I started to see the bigger picture. After many unequal fights with Hibernate, I started to know it better. I started to understand why it does what it does. Today I know that there is an <a href="https://en.wikipedia.org/wiki/Object%E2%80%93relational_impedance_mismatch">object-relational impedance mismatch</a>, which cannot be avoided when using ORM and it’s totally irrational to be upset about it. I wrote about it in my last article: <a href="https://medium.com/kotlin-academy/kotlin-and-jpa-a-good-match-or-a-recipe-for-failure-e52718d93b4f">“Kotlin and JPA — a good match or a recipe for failure?”</a>, in which I focus mainly on cooperation between Kotlin and Hibernate, but you can also read their ORMs in general and about different perspectives on the persistence issue. So if you don’t know what exactly the object-relational impedance mismatch is, feel free to read it.</p><h3>Definitions</h3><p>Let’s start by defining stuff. People tend to use the following terms: <strong>JPA</strong>, <strong>Hibernate, </strong>and<strong> Spring Data JPA</strong> interchangeably like these were just different names for the same thing. But they are not!</p><p><strong>JPA (Java Persistence API)</strong> is an interface specification that describes how to manage relational data in Java applications. So it’s basically just a set of rules to follow. In <a href="https://download.oracle.com/otn-pub/jcp/persistence-2_1-fr-eval-spec/JavaPersistence.pdf">the specification document</a>, you can read e.g. what the constraints for an entity class are, i.e. which rules an entity class has to satisfy to be managed properly by any JPA provider.</p><p>So if there is an interface (<strong>JPA</strong>), there must be an implementation, right? This is basically what <strong>Hibernate</strong> is — an implementation of JPA. The most popular one. The most powerful one. And probably the most hated one.</p><p>Both <strong>Hibernate</strong> and <strong>JPA</strong> expose methods for managing relational data in Java applications, but usually, we don’t operate on that level of abstraction. During the business logic implementation, we shouldn’t need to use <em>EntityManager</em> or <em>HibernateSession </em>directly, because they are just implementation details and the actual domain doesn’t need to know how exactly we’re going to persist the data. So we need to put some abstraction on top of Hibernate/JPA. That’s why the Repository design pattern — introduced at the tactical level of <a href="https://en.wikipedia.org/wiki/Domain-driven_design">Domain Driven Design</a> — is so commonly used and that’s also probably the reason why <a href="https://docs.spring.io/spring-data/jpa/docs/current/reference/html/">Spring Data JPA</a> is so popular.</p><p>It introduces another layer of abstraction, which makes the JPA so convenient and easy to use. Moreover, you don’t need to pick Hibernate when using Spring Data JPA. You might want to use another provider, e.g. <a href="https://eclipse.dev/eclipselink/">EclipseLink</a>.</p><p>Using Spring Data JPA let us avoid a lot of boilerplate code because most of the common usages of JPA are already provided in the implementation of such interfaces as org.springframework.data.jpa.repository.JpaRepository, which is a part of the Spring Data JPA.</p><figure><img alt="Hibernate logo" src="https://cdn-images-1.medium.com/max/1024/0*ZuziaR3NQaeIkwHy.png" /><figcaption>Hibernate logo, source: <a href="https://upload.wikimedia.org/wikipedia/commons/2/22/Hibernate_logo_a.png">Wikipedia</a></figcaption></figure><p>However, hiding the details doesn’t mean we don’t need to know about them. Usually, people use Hibernate with a very simple purpose — “I need to save these changes in the database”. Spring Data JPA is so easy to use (even for the very beginners), that in order to create a simple CRUD application, you don’t need to understand Hibernate at all. You just call repository.save(..) or repository.delete(...).</p><p>That’s why it is usually the first choice when picking up the persistence provider — it’s easy to start. However, it can be really hard to extend your project in the future if you don’t know JPA and Hibernate well. When your application gets popular, performance issues related to the JPA layer might occur. And there is no universal cure for that.</p><p>When it comes to software architecture, many concepts are strongly connected to each other and it’s very hard to discuss any of them separately. Many architecture decisions can impact directly your persistence layer, e.g. poorly separated modules / aggregates (<a href="https://martinfowler.com/bliki/DDD_Aggregate.html">link to Martin Fowler’s definition of aggregate in terms of DDD</a>) can cause too many entities to be connected to each other within a single aggregate or can arise problems with data consistency. Let’s be honest, it’s never just a “Hibernate issue”. If you knew your tool better, you’d use it the way it was designed for, wouldn’t you?</p><p>Hibernate is a very powerful tool, which offers plenty of features and all of them cannot be covered in just one article. So let me focus on some of the most crucial pitfalls, personally selected by me. I will go through:</p><ul><li>pitfalls regarding the JPA entity lifecycle,</li><li>lazy loading trade-offs.</li></ul><p>Let’s start from the very must-know basic knowledge of JPA — the JPA entity lifecycle.</p><h3>JPA Entity Lifecycle</h3><p>When you invoke a constructor of an entity class, you create an entity object in the New (Transient) state. The newly created object isn’t assigned to any row in the database table yet. In order to save (persist) it, you need to call <em>persist</em> method. After that, the entity object changes its state to the Managed, which means that now it’s managed by the Persistence Context, i.e. Hibernate Session<em> </em>in the Hibernate implementation of JPA. When the entity object is in the Managed state, any change you make on it will be detected and propagated to the database within the invocation of the flush method. Usually, you don’t invoke it explicitly (at least you shouldn’t need to do it unless you’re in some very specific situation). The moment in which the <em>flush</em> method is invoked can be configured with the FlushModeType property. By default, it is set to FlushModeType.AUTO. It means that the flush method will be invoked in two situations:</p><ul><li>before the transaction commit,</li><li>before query execution using a database table, for which the current Persistence Context contains any pending changes.</li></ul><figure><img alt="JPA Entity Lifecycle Graph" src="https://cdn-images-1.medium.com/max/621/1*m337fhJoGD_SYmZWFs2R2g.png" /><figcaption>JPA Entity Lifecycle Graph</figcaption></figure><p>If you decide to delete an entity object, you call the remove method and the entity object changes its state to Removed. Similarly to the Managed state, the database will be synchronized within the invocation of the flush method.</p><p>The Managed entity becomes Detached when the Persistence Context (Hibernate Session) is being closed. Usually, you don’t close the session by yourself, because this is already implemented in Spring Data JPA. You can of course detach an entity manually, using Entity Manager / Hibernate Session, but if you take advantage of Spring Data JPA, you operate on the higher level of abstraction, which is Spring Data Repository. Thus, you don’t use Entity Manager / Hibernate Session explicitly.</p><p>Detached means that an entity object is no longer managed by the Persistence Context (Hibernate Session) because it was already closed. So any change made on a detached entity won’t result in synchronization with the database unless it’s merged to the open Persistence Context (Hibernate Session). So any Detached entity can become Managed again if you call the merge method on a detached entity object. In the result of the merge method Hibernate will try to find the entity in the current Persistence Context(Hibernate Session). If it’s there, Hibernate will copy the data from the detached object to the managed one. But if Hibernate doesn’t find the entity in current Persistence Context (Hibernate Session), it will fetch it directly from the database. It’s important to notice here that in some cases calling the repository::save method will result in an additional SELECT statement which is not so obvious at all, especially for beginners.</p><p>Okay, we already have some fundamental knowledge of JPA and Hibernate. But it’s still just theoretical knowledge. Let’s take a look at the code example.</p><p>For readability’s sake, I avoided unnecessary code in the article, so if you’d like to check out the whole source code, you can do it on GitHub <a href="https://github.com/pientaa/hibernate-demo/tree/medium-article">here</a>.</p><h3>Don’t let Hibernate do the magic</h3><p>Take a look at the first example. Let’s discuss a common problem which is TransientPropertyValueException thrown when saving a JPA entity.</p><pre>@Entity<br>class Post(<br>    @Id<br>    @GeneratedValue(strategy = GenerationType.IDENTITY)<br>    var id: Long? = null,<br>    var title: String,<br>    var content: String,<br>    <br>    @ManyToOne<br>    val author: Author,<br>)</pre><pre>@Entity<br>class Author(<br>    @Id<br>    @GeneratedValue(strategy = GenerationType.IDENTITY)<br>    var id: Long? = null,<br>    var firstName: String,<br>    var lastName: String,<br>)</pre><pre>@Repository<br>interface PostRepository : JpaRepository&lt;Post, Long&gt;</pre><p>The example above consists of 2 simple entities: Post and Author, where the first one is in @ManyToOne relationship with the other (that means that Author can have many Posts) and one repository interface — PostRepository, which will be used to save posts with authors.</p><p>Now, let’s take a look at the following test (notice that I’m using <a href="https://kotest.io/docs/framework/testing-styles.html#behavior-spec">BehaviorSpec from Kotest</a>):</p><pre>@SpringBootTest<br>class Test(<br>    private val postRepository: PostRepository<br>) : BehaviorSpec({<br><br>    Given(&quot;Author&quot;) {<br>        val author = Author(firstName = &quot;Jan&quot;, lastName = &quot;Nowak&quot;)<br><br>        When(&quot;Author creates a post&quot;) {<br>            val post = Post(title = &quot;First Post&quot;, content = &quot;Just hanging around&quot;, author = author)<br>            val postId = postRepository.save(post).id<br><br>            Then(&quot;Post is created&quot;) {<br>                postRepository.findByIdOrNull(postId) shouldNotBe null<br>            }<br>        }<br>    }<br>})</pre><p>When you run the test, it’s failing with the message:</p><pre>org.hibernate.TransientPropertyValueException: object references an unsaved transient instance - save the transient instance before flushing : com.pientaa.hibernatedemo.transientPropertyValueException.Post.author -&gt; com.pientaa.hibernatedemo.transientPropertyValueException.Author</pre><p>So when we take a look at the JPA Entity Lifecycle Graph again, it might already be clear what is going on here.</p><figure><img alt="JPA Entity Lifecycle Graph" src="https://cdn-images-1.medium.com/max/621/1*m337fhJoGD_SYmZWFs2R2g.png" /><figcaption>JPA Entity Lifecycle Graph</figcaption></figure><p>The Author object is not following the Post object in the entity’s state transitions. Post gets persisted, so it’s changing its state from Transient to Managed, but the Author object is still in the Transient state. When the Hibernate session closes, Post is flushed, but it still references the transient Author object and that’s why we got the exception.</p><p><a href="https://www.baeldung.com/hibernate-unsaved-transient-instance-error">Baeldung makes it clear</a> that there are two possible solutions to that. However, only one of them is presented in the aforementioned tutorial. They encourage to use cascade parameter in relationship annotation, which in my opinion shouldn’t be the default strategy because the problem we have is not caused just by some wrong usage of Hibernate and its annotations. The actual problem is in the architecture/software design. Why do we need to persist Author and Post at the same time? Does it really need to be the same transaction? Shouldn’t Author and Post be different aggregates? In the real-life example, Author should already exist before the Post is written, shouldn’t it? Otherwise — who is writing the Post?</p><p>In many cases, Hibernate issues can be caused by wrong software design, and using Hibernate features to minimize the consequences of the mistake doesn’t solve the actual problem at all — we just hide it until it escalates, e.g. when new business requirements come to the implementation stage.</p><p>If we just googled TransientPropertyValueException and followed the instructions from Baeldung, we would probably have taken a wrong decision. Baeldung says:</p><blockquote>To cover all scenarios, we need a solution to <strong>cascade our save/update/delete operations for entity relationships that depend on the existence of another entity</strong>. We can achieve that by using a proper <em>CascadeType</em> in the entity associations.</blockquote><p>But what if this particular entity should have already been persisted before we try to associate it with another one? Maybe we’re trying to save too many changes at once and it should be divided into smaller, more domain-like requests. In order to accomplish that, we can create another repository interface — AuthorRepository, to manage Author‘s persistence.</p><pre>@Repository<br>interface AuthorRepository : JpaRepository&lt;Author, Long&gt;</pre><p>Providing another repository interface results in decoupled Author and Post classes which in this case seems reasonable. Notice that even though Author and Post are managed separately, we can still reference the Author entity in Post using the same relationship annotation we did before. Someone will tell that we did not decouple these classes completely, because of that reference we left. And it’s true. It can be decoupled further. But discussion about coupling and decoupling strategies between entities is a good candidate for a separate article. Thus, for the sake of this article’s purpose, let’s keep this relationship. Let’s keep Hibernate busy handling our data access layer and let’s discover more Hibernate features and their pitfalls!</p><h3>Lazy loading — an overused feature?</h3><p>Usually, lazy loading is used to improve performance, but I’ve seen many people using it as a default strategy, even though it is not required at all. Some of them even <a href="https://thorben-janssen.com/5-ways-to-initialize-lazy-relations-and-when-to-use-them/#:~:text=Lazy%20loading%20of%20associations%20between,only%20need%20the%20requested%20entities.">consider it a well-established best practice in JPA</a>:</p><blockquote>Lazy loading of associations between entities is a well established best practice in JPA. Its main goal is to retrieve only the requested entities from the database and load the related entities only if needed. That is a great approach if you only need the requested entities.</blockquote><p>But right after this glorification of lazy loading, we can read in the same article that lazy loading:</p><blockquote>[…] creates additional work and can be the cause of performance problems if you also need some of the related entities.</blockquote><p>The problem is (as usual) not a binary decision like “should I use it or not”, because — “it depends”.</p><p>In an ideal example of a well-designed application with perfectly distilled aggregates, which are small and independent, and changes from one aggregate can affect the other with eventual consistency, there is no need for lazy loading — because every aggregate is small enough to be loaded entirely to the application memory. However, no application is perfect, is it? Quite often we — programmers — need to deal with legacy code and bad architectural decisions (taken mostly because of the deadlines) and it’s much more likely that you end up in a project with multiple entities related to each other with various types of relationships, rather than some well-designed and perfectly distilled software. So it’s totally understandable that the first thing everybody says about JPA optimization is lazy loading.</p><p>Let’s go back to our code example. To enable lazy loading on the Author property in the Post entity, we need to add an additional parameter:</p><pre>@ManyToOne(fetch = FetchType.LAZY)</pre><p>because the default FetchType for @ManyToOne relationship is FetchType.EAGER.</p><p>So now, if we fetch Post from the database using PostRepository, the generated SQL statement should not include any join on the Author table. That’s what we expect from lazy loading, right? But if we refer (accidentally or not) to some fields, not loaded yet, which are meant to be loaded lazily, we should be able to fetch them “on demand”, shouldn’t we? Let’s take a look at the following test:</p><pre>@SpringBootTest<br>@ActiveProfiles(&quot;test&quot;)<br>class PostAuthorLazyLoadingFailingTest(<br>    private val postRepository: PostRepository,<br>    private val authorRepository: AuthorRepository,<br>) : BehaviorSpec({<br><br>    Given(&quot;Author - Jan Nowak&quot;) {<br>        val janNowak = Author(firstName = &quot;Jan&quot;, lastName = &quot;Nowak&quot;).let { authorRepository.save(it) }<br><br>        When(&quot;Jan Nowak creates a Post&quot;) {<br>            val postId = Post(title = &quot;First Post&quot;, content = &quot;Just hanging around&quot;, author = janNowak)<br>                .let { postRepository.save(it) }.id<br><br>            Then(&quot;Fetching lazy loaded property should throw LazyInitializationException&quot;) {<br>                shouldThrow&lt;LazyInitializationException&gt; {<br>                    postRepository.findByIdOrNull(postId)!!.author.firstName shouldBe &quot;Jan&quot;<br>                }<br>            }<br>        }<br>    }<br>})</pre><p>In the test above I save the Author , I save the Post, and after that, I get the Post from the database. Later on, I’m trying to assert the author’s first name, but because of the lazy loading, I’m not allowed to do that. The assertion is failing because of LazyInitializationException:</p><pre>could not initialize proxy [com.pientaa.hibernatedemo.lazyLoading.Author#1] - no Session<br>org.hibernate.LazyInitializationException: could not initialize proxy [com.pientaa.hibernatedemo.lazyLoading.Author#1] - no Session</pre><p>The problem is that Hibernate couldn’t initialize the proxy (used for lazy loading), because “there is no Session”. We need to be really careful using lazy loading in Hibernate, because every time we fetch any lazy-loaded data, we need to have Hibernate Session opened. Well, as I already mentioned at the beginning of the article, we shouldn’t need to use <em>EntityManager</em> or <em>HibernateSession </em>directly, because they are just implementation details. But it turns out that if we’d like to use lazy loading, we should be able to somehow open the session. The question is: what is the right place to do this? Let’s try to answer that question considering the onion architecture.</p><figure><img alt="Onion architecture visualization" src="https://cdn-images-1.medium.com/max/661/1*vpvcNRF6FOdheVW_S34U-A.png" /><figcaption>Onion architecture</figcaption></figure><p>Domain layer? I don’t think so. Domain code should be perfectly clean and framework-agnostic, so there is no place for Hibernate in this layer, especially in a project with a rich domain model, where DDD makes sense.</p><p>Presentation layer? Maybe not a good idea. At some point, it will cause performance issues.</p><p>Application layer? Well, it’s better than the presentation layer (regarding performance), but <em>HibernateSession </em>doesn’t seem to belong anywhere else except the data access / infrastructure layer, especially because we already use an abstraction (JPA) and Hibernate is just an implementation detail (JPA provider), therefore it shouldn’t be exposed in other parts of the application than aforementioned infrastructure layer.</p><p>So it looks like we already know that session boundaries could be set in the application layer, but <em>HibernateSession</em> itself doesn’t fit there. Hmm, I wish there was some kind of an abstraction on top of <em>HibernateSession</em> that could be used in the application layer…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/534/1*uGR81Cx1ma9T-JMV2ErBMw.png" /></figure><p>Exactly! Transactions! It does make sense, doesn’t it? Even from the business perspective, there is something like a transactional consistency — some business processes need to be synchronized and guaranteed to be done as an atomic transaction, but their boundary is bigger than just one aggregate. Thus, the transaction looks like a perfect abstraction on top of <em>HibernateSession</em>. So, all we need is @Transactional which marks a method to be run in the scope of a transaction, therefore it opens the <em>HibernateSession</em> for us.</p><p>Using lazy loading leads to higher complexity, especially when you need to specify transactions to make it work correctly. Don’t use it as a default strategy. Try to consider all alternatives, especially re-designing your aggregates’ boundaries.</p><p>However, LazyInitializationException is not the only pitfall of using lazy loading. Actually, the most popular one is n + 1 problem, which can be really painful when it comes to the application performance.</p><h3>Lazy loading — n + 1 problem</h3><p>Lazy loading is about cutting the primary SQL query to the “minimum”, not loading the lazy loaded data until it’s needed. So we don’t JOIN on a table, which is a lazy-loaded association. However, when the lazy loaded data is needed, we will execute additional SQL statements anyway. This causes the n + 1 problem because the data access layer needs to execute “n” additional SQL statements to get the same data as we could retrieve by the primary query.</p><p>Let’s take a look at the code example again, which I extended by an additional @OneToMany relationship. I won’t go through the details of the best practices regarding this relationship type in Hibernate, because there is already an excellent article about it, which I totally recommend if you’re not familiar with @OneToMany relationship pitfalls:</p><p><a href="https://vladmihalcea.com/the-best-way-to-map-a-onetomany-association-with-jpa-and-hibernate/">The best way to map a @OneToMany relationship with JPA and Hibernate - Vlad Mihalcea</a></p><p>Let’s create a new entity class PostComment.</p><pre>@Entity<br>class PostComment(<br>    @Id<br>    @GeneratedValue(strategy = GenerationType.IDENTITY)<br>    var id: Long? = null,<br>    var content: String,<br><br>    @ManyToOne<br>    val author: Author,<br><br>    @ManyToOne<br>    val post: Post<br>)</pre><p>And let’s extend the current Post class implementation by additional field comments and methods for removing and adding comments to the post.</p><pre>@Entity<br>class Post(<br>    @Id<br>    @GeneratedValue(strategy = GenerationType.IDENTITY)<br>    var id: Long? = null,<br>    var title: String,<br>    var content: String,<br><br>    @OneToMany(mappedBy = &quot;post&quot;, cascade = [CascadeType.ALL], orphanRemoval = true)<br>    val comments: MutableSet&lt;PostComment&gt; = mutableSetOf(),<br><br>    @ManyToOne<br>    val author: Author,<br>) {<br>    fun addComment(content: String, author: Author) {<br>        comments.add(<br>            PostComment(content = content, author = author, post = this)<br>        )<br>    }<br><br>    fun removeComment(commentId: Long) {<br>        comments.removeIf { it.id == commentId }<br>    }<br>}</pre><p>Notice, that I made an author association eagerly loaded because the relationship we’re going to focus on analyzing the n + 1 problem is @OneToMany. This association in Hibernate is lazy-loaded by default.</p><p>The n + 1 problem in our case is n + 1 SELECT statements generated for fetching n Post with their PostComments from the database. Let’s say we have a query (simplified for readability’s sake):</p><pre>select * from post where id &lt; 6</pre><p>which returns 5 Posts. Fetching the Posts’ comments results in 5 additional SELECT statements:</p><pre>select * from post_comment where post_id = 1<br>select * from post_comment where post_id = 2<br>select * from post_comment where post_id = 3<br>select * from post_comment where post_id = 4<br>select * from post_comment where post_id = 5</pre><p>This problem wouldn’t exist if we didn’t use lazy loading. Because instead of additional n SELECT statements, we would have JOIN on post_comment table. Of course, if n is a small number, it doesn’t hurt us, but the problem escalates when this number gets bigger. Notice, that if we made all the associations lazy loaded, there will be n additional SQL statements generated for each association. As you can see, the problem can escalate very quickly if we overuse lazy loading. And again, if this number is huge, maybe the aggregate is too big and the problem is in design, not in the persistence layer itself.</p><p>However, sometimes we need to decide whether JOIN or n additional SELECTs is better for us. Usually, if we’re sure that we’ll need that association to be loaded entirely in the current request, it’s better to fetch it eagerly, using JOIN. But the same entity might be used in another request in which this association is not needed at all. Some kind of hybrid would be perfect, wouldn’t it? And here we’ve got plenty of options, for example:</p><ul><li><a href="https://www.baeldung.com/spring-data-jpa-projections">Spring Data JPA projections</a>,</li><li><a href="https://www.baeldung.com/jpa-entity-graph">JPA Entity Graph</a>,</li></ul><p>and the easiest (in my opinion), which is a simple JPQL query using<br>join fetch explicitly:</p><pre>@Query(&quot;select distinct p from Post p left join fetch p.comments where p.id = :postId&quot;)<br>fun getPostWithComments(@Param(&quot;postId&quot;) postId: Long): Post</pre><p>Taking advantage of the aforementioned JPA options to eagerly fetch a custom set of entity’s associations, you can use FetchType.LAZY as the default FetchType and create projections or for a very specific use case. But it’s still easier and safer not to use FetchType.LAZY at all, so don’t do this unless it’s necessary.</p><h3>Summary</h3><p>As you can see, Hibernate is not as easy as it seems, but for the very basic usage you don’t need to know everything about its tremendous number of features. For any problem you might have, there is always more than one solution. However, there are some very specific cases in which there is the optimal one, which is highly recommended to choose.</p><p>Many problems with the data access layer can be just a result of a wrong application design, so don’t be that hard on Hibernate. It’s not as evil as everybody describes it.</p><p>Remember to use the proper abstraction in your domain code. In complex projects, with rich domain model, you shouldn’t use JPA entities directly in your domain code.</p><p>Thanks for reading.</p><p>If you’re looking for a comprehensive source of knowledge regarding JPA/Hibernate, I strongly recommend the book <a href="https://vladmihalcea.com/books/high-performance-java-persistence/">“High-Performance Java Persistence” by Vlad Mihalcea</a>. Or maybe you feel like there are some JPA/Hibernate-related topics you’d like me to write about — just let me know!</p><p>I’d like to thank <a href="https://medium.com/u/52b77f020913">Adrian Glapiński</a> and <a href="https://medium.com/u/dddcafb2a42e">Paweł Dereziński</a> for being very helpful in reviewing my article. I appreciate it a lot!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=84ca72b959c3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/hibernate-is-not-so-evil-84ca72b959c3">Hibernate is not so evil</a> was originally published in <a href="https://betterprogramming.pub">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kotlin and JPA — a good match or a recipe for failure?]]></title>
            <link>https://medium.com/kotlin-academy/kotlin-and-jpa-a-good-match-or-a-recipe-for-failure-e52718d93b4f?source=rss-7ec306a61a06------2</link>
            <guid isPermaLink="false">https://medium.com/p/e52718d93b4f</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[hibernate]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Łukasz Pięta]]></dc:creator>
            <pubDate>Fri, 24 Feb 2023 06:09:36 GMT</pubDate>
            <atom:updated>2024-08-06T06:43:40.217Z</atom:updated>
            <content:encoded><![CDATA[<h3>Kotlin and JPA — a good match or a recipe for failure?</h3><h4>How to use Hibernate in Kotlin in the most efficient way</h4><figure><img alt="Kotlin &amp; JPA — photo from presentation @ 4Developers" src="https://cdn-images-1.medium.com/max/1024/1*SX1krl8P-CJf7R2fNUT4QQ.jpeg" /><figcaption>Photo by <a href="https://www.facebook.com/fotografia.michallis">Michał Lis</a></figcaption></figure><p>Kotlin and Hibernate might be confusing, especially for the very beginners. It’s hard to know all the stuff in the moment you’ve just started using these two technologies. There are pitfalls which you should be familiar with before writing a single line of code using Kotlin and JPA. After reading this article you’ll have a broader perspective on the eternal hate towards ORMs, especially Hibernate, especially mixed with Kotlin.</p><h3>Object-Relational Mapping — difference of opinions</h3><blockquote>Hibernate makes trivial things easier and non-trivial things more complex with dozens of gotchas.</blockquote><blockquote>A proper abstraction layer adds a tiny sacrifice for easy things in order to simplify more complex things.</blockquote><blockquote>Hibernate got it backwards and I would even call it an anti-pattern.</blockquote><p>The above is <a href="https://www.reddit.com/r/Kotlin/comments/v97i7d/comment/ibvpxwl/?utm_source=share&amp;utm_medium=web2x&amp;context=3">an actual opinion about Hibernate shared on Reddit</a>. This is just one of many negative ones. <a href="https://www.reddit.com/r/Kotlin/comments/v97i7d/comment/ibv1gmp/?utm_source=share&amp;utm_medium=web2x&amp;context=3">As you can read further in the same thread, there is another opinion of another Reddit user</a> (original spelling):</p><blockquote>I think JPA and Kotlin are no good match. In Kotlin you try to make everything immutable and initialized on construction. JPA uses opposite paradigms.</blockquote><blockquote>Be aware that JPA’s field population via reflection and proxies can ignore your init-blocks. Also be aware that the the plugin to create a no-arg constructors will ignore init-blocks and class-internal value assignments which would normally occur during object construction.</blockquote><p>I read and heard lots of opinions like that. It made me thinking that Kotlin and JPA might really not be the best match. So I googled up more and it turned out that Hibernate is not the only ORM being hated on the internet. Generally speaking, the whole idea of ORM seems to upset people a lot. Let’s have a look at <a href="https://www.yegor256.com/2014/12/01/orm-offensive-anti-pattern.html">Yegor’s opinion</a>:</p><blockquote>ORM is a terrible anti-pattern that violates all principles of object-oriented programming, tearing objects apart and turning them into dumb and passive data bags. There is no excuse for ORM existence in any application, be it a small web app or an enterprise-size system with thousands of tables and CRUD manipulations on them.</blockquote><p>He proposed the alternative approach, which he called <strong>SQL-speaking objects</strong>, which basically means, that inside all domain objects there will be an implementation of connection to the database (using plain JDBC) regarding all CRUD operations on specific tables. This is how it would look like for the domain object Post:</p><figure><img alt="SQL-speaking object visualization" src="https://cdn-images-1.medium.com/max/272/1*ZHQ-1S_A16cQEJ8fBNneOQ.png" /><figcaption><a href="https://www.yegor256.com/2014/12/01/orm-offensive-anti-pattern.html#sql-speaking-objects">SQL-speaking objects</a> by <a href="https://www.yegor256.com/"><strong>Yegor Bugayenko</strong></a></figcaption></figure><p>So he is like Drake on this meme:</p><figure><img alt="Meme about Hibernate already handling all JDBC issues" src="https://cdn-images-1.medium.com/max/500/1*LeOPk_fP-ZUWW1ck1GvFrA.png" /></figure><p>and I don’t get it at all.</p><p>Imagine now that Post will change, e.g. some field changed its name or a new field was added to the entity class. Good luck with applying changes in plain SQL every time you do this little change in your persistence layer. But this is not the main reason why we shouldn’t use plain JDBC connection, which is obviously hard to maintain and debug. There are lots of other disadvantages of “SQL-speaking object”, e.g. security issues, which are already solved by ORMs like Hibernate.</p><h3>Vlad Mihalcea on Twitter: &quot;To abstract the communication protocol, yes. But, the reason there are so many Java data access framework is that the API is way too verbose and prone to DB-specific hacks. / Twitter&quot;</h3><p>To abstract the communication protocol, yes. But, the reason there are so many Java data access framework is that the API is way too verbose and prone to DB-specific hacks.</p><p>However, voices <a href="https://www.yegor256.com/2014/12/01/orm-offensive-anti-pattern.html">like that of Yegor</a> are nothing specific to the present times. It’s not like Hibernate or any other ORM did something unforgivably evil — since people started using ORMs, opinions like that have been appearing on the internet periodically. I’d even call it a constant trend. In 2012, there was <a href="https://martinfowler.com/bliki/OrmHate.html">an article written by Martin Fowler commenting the whole “ORM hate” movement</a>. Martin Fowler writes in his article:</p><blockquote>So ORMs help us deal with a very real problem for most enterprise applications. It’s true they are often misused, and sometimes the underlying problem can be avoided. They aren’t pretty tools, but then the problem they tackle isn’t exactly cuddly either. I think they deserve a little more respect and a lot more understanding.</blockquote><p>As you can see, eventually he stands up for ORMs, because the problem they solve is very tough. Object-relational mapping isn’t easy at all, because of the problem’s nature, i.e. mapping between two very different worlds: object-oriented and relational.</p><h3>Object-relational impedance mismatch</h3><p>Object-oriented programming is all about <strong>abstraction</strong>, <strong>encapsulation</strong>,<strong> inheritance</strong>,<strong> </strong>and <strong>polymorphism</strong>. These are four main principles of OOP. Relational databases, in contrast, are focused on relationship itself. So, on the one hand we have <strong>classes</strong> with <strong>methods</strong> changing their <strong>state</strong> and <strong>behavior</strong>. On the other hand we have <strong>tables</strong> which consists of <strong>columns </strong>and <strong>rows</strong>, where each table can be referenced by another table using <strong>foreign key</strong>.</p><figure><img alt="Object-relational impedance mismatch visualization" src="https://cdn-images-1.medium.com/max/1017/1*IjNBgD9KbQ-QRW51wLyObA.png" /><figcaption>Object-relational impedance mismatch</figcaption></figure><p>So the question is: how can anyone express OOP principles in relational database? To this day, there is no simple answer to it. Actually, there might not be any satisfying answer at all. You just cannot express concepts from OOP in relational world. It’s just not possible. Even if you try to describe your model mathematically, you end up with different structures: OOP can be expressed by a directed graph,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/1*W55ZlRJlVmp5iAANriyIuA.png" /><figcaption>Example of directed graph</figcaption></figure><p>whereas relational database model is undirected graph, because inner join is a symmetric operation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/704/1*1mIxwKqxUD8Ue97itcsvvg.png" /><figcaption>Example of undirected graph</figcaption></figure><p>So there is no easy solution when it comes to the object-relational mapping. Every ORM solves very difficult problem of mapping between these two significantly different worlds. Knowing that, we might start to understand why these tools can’t be prettier and more user friendly. ORM is a compromise — contract between relational database and behavioral objects. There wouldn’t be any problem if we didn’t need mapping i.e. we wouldn’t use SQL database or we wouldn’t use object-oriented paradigm. But if we want exactly these tools on both sides, we need to agree upon some compromise, and ORM is exactly that. “It is what it is”, right? If you’ve been in IT for some time you must already know that it’s all about trade-offs. There is no Holy Grail in programming and software architecture. You just need to adjust your toolbox to what your problem is and what the drivers of your decision are. And that’s all. So basically the question is — do you need ORM? Maybe there are some other solutions, which solve your problem in a more efficient way? Let’s see what alternatives we’ve got.</p><h3>Not only SQL</h3><p>There are some alternatives to ORMs, of course. You can choose one of many NoSQL databases instead of relational one.</p><figure><img alt="Meme about Hibernate being jaleous of NoSQL databases" src="https://cdn-images-1.medium.com/max/750/1*Iix9y_ipfW8XKpq9BAmsSA.png" /></figure><p>As you can see at the meme above, Hibernate was so jealous of NoSQL databases, that it started supporting NoSQL data sources, too. There was even a project called <a href="https://hibernate.org/ogm/">Hibernate OGM</a>, but it’s not supported anymore. As we can read <a href="https://hibernate.org/ogm/support/">here</a>:</p><blockquote>Hibernate OGM is not yet part of any of Red Hat’s fully supported products.</blockquote><p>It’s too bad, I liked their motto a lot:</p><blockquote>The power and simplicity of JPA for NoSQL datastores. Including support for associations, sub-classes, queries and much more.</blockquote><p>However, I’m probably in an exclusive group of very few people having good feelings for JPA and its “simplicity” as they call it. 😂</p><p>Of course, Hibernate leaving support for NoSQL doesn’t mean we can’t use noSQL data sources for JVM applications. It’s still quite easy to use (supposedly easier than SQL) and usually people enjoy doing it. However, the chosen type of data source may depend on many factors and it might happen that relational database is just a better fit. Because, you know, not every problem can be solved by any tool, right?</p><h3>Hibernate and Kotlin (impedance mis)match</h3><p>So if NoSQL does not solve our problems well enough (it doesn’t have to be true, but let’s assume so), and we don’t want to reinvent the wheel again (which — in my opinion — SQL-speaking objects are), let’s discuss why Hibernate is considered not to be a good match with Kotlin — truely or not, you will decide later.</p><figure><img alt="Hibernate logo" src="https://cdn-images-1.medium.com/max/1024/0*ZuziaR3NQaeIkwHy.png" /><figcaption>Source: <a href="https://upload.wikimedia.org/wikipedia/commons/2/22/Hibernate_logo_a.png">Wikipedia</a></figcaption></figure><p><strong>Hibernate</strong>, very mature ORM for Java applications, the most popular among all JPA providers — probably the most hated, too, but I might be biased by my JVM-based bubble of interests.</p><figure><img alt="Kotlin logo" src="https://cdn-images-1.medium.com/max/512/0*j93OcRLWlKvaLVPl" /><figcaption>Source: <a href="https://upload.wikimedia.org/wikipedia/commons/d/d4/Kotlin_logo.svg">Wikipedia</a></figcaption></figure><p>And <strong>Kotlin</strong> — very young “not-only-JVM” language (it’s only 7 years old! 😱), wildly gaining in popularity, especially among ex-Java developers (coming from both Android and server-side).</p><p>Hibernate itself “just implements”<a href="https://download.oracle.com/otn-pub/jcp/persistence-2_1-fr-eval-spec/JavaPersistence.pdf"> JPA Specification</a>, so it’s not the Hibernate’s fault that specification consist of many restrictions, which might introduce some limitations. However, when people establish some new rule, they do it usually in order to be more effective, e.g. it wouldn’t be possible to ride a car so fast if there was no rule of riding just one side of road in each direction. The same applies to any rule of clean code or design patterns or even a paradigm in software development. We set up rules to instantly improve our work. That’s why there is a standard for managing persistence layer for Java applications, which is called JPA (Java Persistence API). JPA among other things, standardizes entity life cycle:</p><figure><img alt="JPA entity graph" src="https://cdn-images-1.medium.com/max/621/1*1RCkJj8XyEE0vfKYawqGtQ.png" /><figcaption>JPA entity graph</figcaption></figure><p>This graph might be very useful when debugging JPA-related errors like “Detached entity passed to persist”. But most important for us will be the following rules from JPA Specification, which are in conflict with Kotlin philosophy:</p><blockquote>1. The entity class must have a no-arg constructor. The entity class may have other constructors as well. The no-arg constructor must be public or protected.<br>2. The entity class must not be final. No methods or persistent instance variables of the entity class may be final.</blockquote><p>What’s wrong with these rules?</p><ol><li><strong>“The entity class must have a no-arg constructor.”</strong> Really? Do I really need to create a no-arg constructor for each entity class? First of all, that’s a lot of code duplication. Second of all — and what’s more important here — it might be a violation of domain invariants. Having non-nullable properties in Kotlin we might not want to make our properties nullable at all, especially if our domain does not require them to be optional or even force us not to. And here comes the ORM-hate argument about ORM violating OOP principles. Hibernate needs a no-arg constructor to create an empty object and fill the object with values after it’s created. RIP encapsulation. But, fortunately, there is already <a href="https://kotlinlang.org/docs/no-arg-plugin.html#jpa-support">kotlin-jpa</a> compiler plugin which basically generate no-args constructors for us. These constructors will be generated in the bytecode of each entity-related class: @Entity, @MappedSuperclass and @Embeddable.</li><li><strong>“The entity class must not be final. No methods or persistent instance variables of the entity class may be final</strong>.<strong>”</strong> In Kotlin each class with all its properties is final by default. So we need to somehow open all entity classes. We could just use the keyword open , but luckily we don’t need to do it manually. There is another compiler plugin — <br><a href="https://kotlinlang.org/docs/all-open-plugin.html">all-open</a>, which works similarly as the previously mentioned kotlin-jpa compiler plugin, but this time we need to define which annotations indicate classes to be opened.</li></ol><p>After configuring these two plugins in your Gradle/Maven file, you can now use JPA with Kotlin. But there is still at least one Kotlin-specific pitfall you should know about.</p><h3>Data class vs JPA Entity</h3><p>Data class is one of my favorite Kotlin features. It has equals(),hashCode() toString() and copy() methods already implemented considering all properties declared in a primary constructor. Let’s define the following class in Kotlin:</p><pre>data class Person(val name: String)</pre><p>In plain Java it would be something like that:</p><pre>public class Person {<br>    private String name;<br><br>    public Person(String name) {<br>        this.name = name;<br>    }<br><br>    public String getName() {<br>        return name;<br>    }<br><br>    public void setName(String name) {<br>        this.name = name;<br>    }<br><br>    @Override<br>    public boolean equals(Object o) {<br>        if (this == o) return true;<br>        if (o == null || getClass() != o.getClass()) return false;<br>        Person person = (Person) o;<br>        return Objects.equals(name, person.name);<br>    }<br><br>    @Override<br>    public int hashCode() {<br>        return Objects.hash(name);<br>    }<br><br>    @Override<br>    public String toString() {<br>        return &quot;Person{&quot; +<br>                &quot;name=&#39;&quot; + name + &#39;\&#39;&#39; +<br>                &#39;}&#39;;<br>    }<br><br>    public Person copy(String name) {<br>        return new Person(name);<br>    }<br><br>    public Person copy() {<br>        return new Person(this.name);<br>    }<br>}</pre><p>Of course nobody writes Java this way anymore. Every Java developer would just use <a href="https://projectlombok.org/">Lombok</a>.</p><p>Although there is already record in Java, it lacks OOP concepts, in contrast to Kotlin data class. Java record doesn’t allow us to inherit from other class or interface. Java record can’t have any non-static member. So if you look at the following Kotlin data class, you might see how much different these two concepts are.</p><pre>interface Bar<br>open class Foo(open val name: String)<br>data class FooBar(override val name: String) : Foo(name), Bar {<br>    private lateinit var foo: String<br>}</pre><p>Moreover, record has no copy() function, which is great built-in implementation of <a href="https://refactoring.guru/design-patterns/prototype">Prototype</a> pattern in Kotlin language syntax.</p><p>However, data class is not recommended to be used for JPA entity, because it’s immutability predispositions and default implementation of equals(), hashCode() and toString() conflict with JPA Specification. There are already very good articles about it, which I strongly recommend to be familiar with:</p><ul><li><a href="https://vladmihalcea.com/the-best-way-to-implement-equals-hashcode-and-tostring-with-jpa-and-hibernate/">The best way to implement equals, hashCode, and toString with JPA and Hibernate - Vlad Mihalcea</a></li><li><a href="https://www.jpa-buddy.com/blog/best-practices-and-common-pitfalls/">Best Practices and Common Pitfalls of Using JPA (Hibernate) with Kotlin</a></li></ul><p>The rules of thumb for data class as JPA entity are:</p><ol><li>Use aforementioned plugins: <a href="https://kotlinlang.org/docs/no-arg-plugin.html#jpa-support">kotlin-jpa</a>, <a href="https://kotlinlang.org/docs/all-open-plugin.html">all-open</a>.</li><li>Always override equals(), hashCode() and toString(). Example of JPA Entities with properly overridden equals(), hashCode() and toString():</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7a260e1148956982cdc299d6448d44d4/href">https://medium.com/media/7a260e1148956982cdc299d6448d44d4/href</a></iframe><p>As you can see, a lot of boilerplate code appeared when we tried to use data class for JPA entity. Most people just don’t recommend doing that, but I’d say — you can do this, but it might not be worth it. However, there is one more thing regarding using data class for JPA entity — data class is final and it can’t be “opened” manually; compiler won’t let us do that, unless we use <a href="https://kotlinlang.org/docs/all-open-plugin.html">all-open</a> compiler plugin. But then it turns out that it’s possible to open data class 😱. And the bytecode looks really disturbing:</p><pre>@javax.persistence.Entity public open data class Post</pre><p>Unfortunately, I can’t tell you for sure if it’s not going to generate some serious issues in the future, because obviously it’s just breaking the data class contract, which is: data class must be final. There was even an <a href="https://youtrack.jetbrains.com/issue/KT-34568/All-open-plugin-does-not-support-data-classes">issue for that</a> and following response from JetBrains:</p><blockquote>[…] breaking <em>data class</em> contracts will eventually bring more harm than good.</blockquote><p>So data class is cool, but it seems reasonable not to use it as JPA entity. In that case, let’s remove data keyword. However, overriding equals(), hashCode() and toString() is still a good idea, because they <strong>must satisfy JPA standards</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6ea76badd931a183bee72456a98356c9/href">https://medium.com/media/6ea76badd931a183bee72456a98356c9/href</a></iframe><p>Nobody will praise these entities for their conciseness, elegance and expressiveness, because they are not like that. We simply lost the power of Kotlin. And is there anything we could do about it?</p><p>Well, first of all, let’s answer the question: why does the JPA layer dirt hurt us? These classes’ design has several drawbacks:</p><ul><li>validation of rule: “prefer val over var”,</li><li>boilerplate code ( equals(), hashCode(), toString()),</li><li>annotations (if you don’t agree it’s a drawback, I highly recommend watching <a href="https://www.youtube.com/watch?v=-6zT60l5hDc">this presentation by Jarosław Ratajski</a>).</li></ul><p>However, if it’s crucial to make Hibernate doing its best, can we do anything to minimize the pain? And here comes the onion’s architecture!</p><h3>Onion architecture 🧅</h3><figure><img alt="Meme about applications being like onions because of having layers" src="https://cdn-images-1.medium.com/max/652/1*CuH_WpixAOVBN7EFBfCsYw.jpeg" /></figure><p>If JPA entities are dirty and we don’t consider them as good candidates for domain objects, we can push whole JPA layer to the infrastructure in the <strong>onion architecture</strong>.</p><figure><img alt="Onion architecture visualization" src="https://cdn-images-1.medium.com/max/661/1*vpvcNRF6FOdheVW_S34U-A.png" /><figcaption>Onion architecture</figcaption></figure><p>The main concept of onion architecture is that <strong>dependencies always point inwards</strong>, i.e. a layer can use only layers inside itself. Although there are plenty of variants (with different number of layers) of onion architecture, all of them have <strong>“Domain” in the most inner layer</strong>. That’s the heart of an application, this is the place in which we put business logic.</p><p>So if JPA Entity is “dirty” and we don’t want out business logic to depend on that, we can make a use of this architectural design pattern.</p><p>Let’s say that in domain package we have following Person class:</p><pre>data class Person(<br>    val id: UUID,<br>    val firstName: String,<br>    val lastName: String,<br>)</pre><p>and a Repository interface:</p><pre>interface PersonRepository {<br>    fun save(person: Person): Person<br>    fun getById(id: UUID): Person<br>}</pre><p>So in infrastructure package we can put following JPA repository interface:</p><pre>@Repository<br>interface PersonEntityRepository : JpaRepository&lt;Person, UUID&gt;</pre><p>and JPA entity:</p><pre>@Entity<br>@Table(name = &quot;person&quot;)<br>class PersonEntity(<br>    @Id<br>    val id: UUID,<br>    var firstName: String,<br>    var lastName: String,<br>) {<br>    override fun equals(other: Any?): Boolean {<br>        if (this === other) return true<br>        if (other == null || Hibernate.getClass(this) != Hibernate.getClass(other)) return false<br>        other as PersonEntity<br><br>        return id == other.id<br>    }<br><br>    override fun hashCode(): Int = javaClass.hashCode()<br><br>    @Override<br>    override fun toString(): String {<br>        return this::class.simpleName + &quot;(id = $id , firstName = $firstName , lastName = $lastName )&quot;<br>    }<br>}</pre><p>and use them in following PersonRepository implementation:</p><pre>class PersonRepositoryImpl(<br>    private val personEntityRepository: PersonEntityRepository<br>) : PersonRepository {<br>    override fun save(person: Person): Person =<br>        personEntityRepository.save(person.toEntity()).toDomain()<br><br>    override fun getById(id: UUID): Person =<br>        personEntityRepository.getReferenceById(id).toDomain()<br>}<br><br>private fun PersonEntity.toDomain() = Person(id, firstName, lastName)<br>private fun Person.toEntity(): PersonEntity = PersonEntity(id, firstName, lastName)</pre><p>This way, we’ve written much more code, but what we achieved might be worth it:</p><ul><li>domain logic <strong>does not depend </strong>on persistence layer,</li><li>we can have <strong>different models</strong> for domain and JPA,</li><li><strong>loose connection</strong> between business logic and persistence layer makes it open for future changes, e.g. it’s possible to migrate to NoSQL easily,</li><li>there could be <strong>more implementations</strong> of PersonRepository, e.g. in-memory database for testing purpose.</li></ul><p>In CRUD-like systems it would be an over-engineering to use onion architecture, but when building complicated systems with very rich domain, it’s crucial to make your domain framework-agnostic. Domain can change a lot, because requirements change all the time, don’t they? So if you make your domain depend on the persistence layer, it’ll be hard to: 1. test it, 2. adjust to changing requirements.</p><h3>Conclusions</h3><p>At first sight, Hibernate and Kotlin seem not to be the best match. Especially because Hibernate is written in Java and there are lots of differences between Java and Kotlin. But after going through all pitfalls, we see that all of them have already been solved by e.g. compiler plugins or official recommendations for Hibernate and Kotlin. So if we agree upon a compromise, which ORM is itself, and we understand the tools we’re using, there is nothing wrong in choosing Hibernate as a persistence provider for Kotlin server-side application. Of course, there are Kotlin-based lightweight ORMs like <a href="https://github.com/JetBrains/Exposed">Exposed</a> and they can replace Hibernate in your application, sure, why not. It’s your toolbox, it’s up to you, but choose wisely. So, no matter the decision, please keep in mind the object-relational impedance mismatch, which cannot be avoided at all. Don’t be frustrated by ORMs. They aren’t the prettiest tools, nobody argues that. But you don’t need to pollute your pure domain by JPA entities. You can hide the dirty JPA implementation in an infrastructure layer thanks to the onion architecture.</p><p>Thanks for reading my article! Hope you enjoyed it! Please, share your opinion with me. You can do this either in comment section or DM.</p><p>If you’d like to read more about Hibernate pitfalls, you can take a look at my article: <a href="https://medium.com/@pientaa/hibernate-is-not-so-evil-84ca72b959c3">“Hibernate is not so evil — You just don’t know it well enough”</a>.</p><p>If you’re curious about the null safety comparison between Java and Kotlin, you should check out my article: <a href="https://medium.com/kotlin-academy/null-safety-bb20b0cbf1a4">“Null Safety — Why Java will never catch up to Kotlin”</a>.</p><p>I’d like to thank <a href="https://medium.com/u/52b77f020913">Adrian Glapiński</a> and <a href="https://medium.com/u/dddcafb2a42e">P Derezinski</a> for being very helpful with reviewing my article.</p><figure><a href="https://kt.academy/article?utm_source=promocjaartykulu&amp;utm_medium=medium&amp;utm_campaign=KotlinAndJPA"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mTUC4mzwsTzhzuDDUagtSQ.jpeg" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e52718d93b4f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/kotlin-academy/kotlin-and-jpa-a-good-match-or-a-recipe-for-failure-e52718d93b4f">Kotlin and JPA — a good match or a recipe for failure?</a> was originally published in <a href="https://medium.com/kotlin-academy">kt.academy</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>