Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Kotlin support Ormlite in 100%? (Data classes)

I'm new to Kotlin and I wish to convert my java model classes with data classes, is it possible? I mean does Ormlite support this?

like image 698
Zeezl Avatar asked Feb 19 '16 15:02

Zeezl


2 Answers

I'm using OrmLite with Kotlin's data classes with no problem. The key is to specify default values for all fields, then Kotlin generates an empty constructor for the data class:

@DatabaseTable(tableName = "sample_table")
data class SampleRecord(
        @DatabaseField(id = true)
        var id: String? = null,

        @DatabaseField(canBeNull = false)
        var numField: Int? = null,

        @DatabaseField
        var strField: String = "",

        @DatabaseField
        var timestamp: Date = Date()
)

» Working example on GitHub

like image 73
juzraai Avatar answered Oct 13 '22 10:10

juzraai


I converted my daos to normal classes without problems

import com.j256.ormlite.field.DatabaseField
import com.j256.ormlite.table.DatabaseTable

@DatabaseTable(tableName = HabitDao.TABLE)
class HabitDao() {

    companion object {
        const val TABLE = "habitdao"
        const val ORDER = "order"
        const val ID = "id"
    }

    @DatabaseField(columnName = ID, generatedId = true)
    var id: Int = 0

    @DatabaseField(index = true)
    lateinit var title: String

    @DatabaseField
    lateinit var intention: String

    @DatabaseField(columnName = ORDER)
    var order: Int = 0

    constructor(title: String, intention: String) : this() {
        this.title = title
        this.intention = intention
    }

    override fun toString(): String {
        return title
    }
}

You just need to provide empty constructor (see the one in the class definition). Also lateinit makes properties easier to use later on.

Edit: Data classes seem to add features that are useful when you need to serialize those objects. Ormlite is able to handle normal a.k.a. Java classes already so there is no need to do that. Moreover data class is expected to contain all its fields in the constructor and you don't want the id field to be present there.

like image 43
damienix Avatar answered Oct 13 '22 10:10

damienix