【问题标题】:Does Kotlin support Ormlite in 100%? (Data classes)Kotlin 是否 100% 支持 Ormlite? (数据类)
【发布时间】:2016-06-01 06:04:53
【问题描述】:

我是 Kotlin 的新手,我希望将我的 java 模型类转换为数据类,这可能吗?我的意思是 Ormlite 支持这个吗?

【问题讨论】:

  • 我用 JPA 试过了,但它在 Kotlin 上运行得不太好,这是我的问题:stackoverflow.com/questions/32038177/…。不过不知道 Ormlite,如果知道的话会很高兴。
  • 你能解释一下 Ormlite 如何使用类吗?它是否构造它们,如果是,它是否需要一个空的默认构造函数?你尝试过实验吗?

标签: android ormlite kotlin


【解决方案1】:

我将 OrmLite 与 Kotlin 的数据类一起使用没有问题。关键是为所有字段指定默认值,然后 Kotlin 为数据类生成一个空的构造函数:

@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

【讨论】:

  • 如果属性是 vals,这似乎不起作用
  • @starkej2 当然,因为 OrmLite 使用 noarg 构造函数 + 设置器,而 vals 没有设置器。
  • 我以为 OrmLite 使用反射来初始化属性? @juzraai stackoverflow.com/a/16780928/1169961
  • 好吧,那我上面的评论错了。 :) 所以它适用于 Java 中的 final 字段,但不适用于 Kotlin 中的 vals?
【解决方案2】:

我将我的 daos 转换为正常的类没有问题

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
    }
}

您只需要提供空的构造函数(参见类定义中的构造函数)。此外,lateinit 使属性在以后更易于使用。

编辑:当您需要序列化这些对象时,数据类似乎添加了有用的功能。 Ormlite 已经能够处理普通的 a.k.a. Java 类,因此无需这样做。此外,数据类应在构造函数中包含其所有字段,并且您不希望 id 字段出现在那里。

【讨论】:

    【解决方案3】:

    不,ORMLite 不能用于 Kotlin 数据类(从 1.1.2 版开始),因为 ORMLite 要求使用 @DatabaseField 注释字段,而使用数据类语法声明的字段则无法做到这一点。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-18
      相关资源
      最近更新 更多