Search code examples
kotlinjdbidata-class

Generate data class attribute value only during creation


I have a data class Supplier defined in my models:

data class Supplier (
        val id: Int = 0,
        val name: String,
        val owner: String,
) {
    companion object {
        private const val prefix = "SUP"

        private fun generateId(): String {
            return prefix + UUID.randomUUID().toString()
        }
    }

    val supplierId = generateId()
}

I have a generated supplierId to generate a new identifier for each supplier that is created.

Once I create a new Supplier and save to a database, the supplierId is stored.


The issue is when I want to query a Supplier object based on an id provided by the user. The Dao implementation of the query function:

@SqlQuery("select $SUPPLIER_COLS from $TABLE_NAME where supplier_id = :supplier_id")
fun getSupplier(@Bind("supplier_id") supplierId: String): Supplier?

This function gets the correct row from the database, but when it returns the object by generating one again, a new supplierId is generated as part of it.


How do I modify my implementation such that the generator works only for the first time and not when reading from the database.

One way I can think of it is to generate the id before creating the object and pass that as a parameter. Doing this would mean that my class signature will not immediately tell me what is a generated field and what is not. Is there any other approach I can take?


Solution

  • Try to make supplierId as a constructor parameter with the default value like this:

    data class Supplier(
        val supplierId: String = generateId(),
        val id: Int = 0,
        val name: String,
        val owner: String
    ) {
        companion object {
            private const val prefix = "SUP"
    
            private fun generateId(): String {
                return prefix + UUID.randomUUID().toString()
            }
        }
    }
    

    If you are using jdbi/kotlin RowMapper it should work with no additional changes.