58 lines
1.6 KiB
Kotlin
58 lines
1.6 KiB
Kotlin
package nl.astraeus.nl.astraeus.persistence.reference
|
|
|
|
import nl.astraeus.nl.astraeus.persistence.Persistable
|
|
import nl.astraeus.nl.astraeus.persistence.currentTransaction
|
|
import java.io.Serializable
|
|
import kotlin.reflect.KProperty
|
|
|
|
inline fun <reified T : Persistable> reference(
|
|
initialValue:T
|
|
) = Reference(T::class.java, initialValue)
|
|
|
|
inline fun <reified T : Persistable> nullableReference(
|
|
initialValue:T? = null
|
|
) = NullableReference(T::class.java, initialValue)
|
|
|
|
class Reference<S : Persistable>(
|
|
val cls: Class<S>,
|
|
initialValue: S
|
|
) : Serializable {
|
|
var id: Long = initialValue.id
|
|
|
|
operator fun getValue(thisRef: Persistable, property: KProperty<*>): S {
|
|
return currentTransaction()?.find(cls.kotlin, id) ?: throw IllegalStateException("Reference not found")
|
|
}
|
|
|
|
operator fun setValue(thisRef: Persistable, property: KProperty<*>, value: S) {
|
|
currentTransaction()?.store(value)
|
|
id = value.id
|
|
}
|
|
|
|
companion object {
|
|
private const val serialVersionUID: Long = 1L
|
|
}
|
|
}
|
|
|
|
class NullableReference<S : Persistable>(
|
|
val cls: Class<S>,
|
|
initialValue: S? = null
|
|
) : Serializable {
|
|
var id: Long? = initialValue?.id
|
|
|
|
operator fun getValue(thisRef: Persistable, property: KProperty<*>): S? {
|
|
return currentTransaction()?.find(cls.kotlin, id ?: 0L)
|
|
}
|
|
|
|
operator fun setValue(thisRef: Persistable, property: KProperty<*>, value: S?) {
|
|
if (value != null) {
|
|
// todo: only store if not already stored?
|
|
currentTransaction()?.store(value)
|
|
}
|
|
id = value?.id
|
|
}
|
|
|
|
companion object {
|
|
private const val serialVersionUID: Long = 1L
|
|
}
|
|
}
|