2016-02-19 74 views
2

我是Kotlin的新手,我希望將我的java模型類與數據類進行轉換,這有可能嗎?我的意思是Ormlite是否支持這個?Kotlin 100%支持Ormlite嗎? (Data classes)

+1

我JPA試了一下,它不與科特林工作得非常好,這裏是我的問題:http://stackoverflow.com/questions/32038177/kotlin-with-jpa-default-constructor-hell。雖然不知道Ormlite,但如果它確實會很高興。 – hotkey

+0

你能解釋一下Ormlite如何使用類?它構造它們,如果是這樣,它需要一個空的默認構造函數?你嘗試過一個實驗嗎? –

回答

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字段在該處存在。

0

不,ORMLite不能與Kotlin數據類(版本1.1.2以上)一起使用,因爲ORMLite要求使用@DatabaseField註釋字段,這對於使用數據類語法聲明的字段是不可能的。

1

我用OrmLite和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