https://kotlinlang.org logo
#exposed
Title
# exposed
f

Fernando Sanchez (Perraco Labs)

03/09/2024, 12:03 PM
Is there a way in Exposed, similar to *Hibernate*'s
@CreationTimestamp
and
@UpdateTimestamp
annotations, to automatically handle the creation and update timestamps for entity fields?
b

Berkay Özkan

03/09/2024, 12:06 PM
We use Entityhook for DAO like this:
Copy code
EntityHook.subscribe { action ->
            val now = Instant.now().toEpochMilli()
            if (action.changeType == EntityChangeType.Updated) {
                action.toEntity(this)?.lastModifiedBy = Headers.USER_MAIL.getOrDefault()
                action.toEntity(this)?.lastModifiedDate = now
            }
            if (action.changeType == EntityChangeType.Created) {
                action.toEntity(this)?.lastModifiedBy = Headers.USER_MAIL.getOrDefault()
                action.toEntity(this)?.lastModifiedDate = now
                action.toEntity(this)?.createdBy = Headers.USER_MAIL.getOrDefault()
                action.toEntity(this)?.createdDate = now
                action.toEntity(this)?.deleted = false
            }
And for DSL:
Copy code
fun <T : BaseTable> T.update(
    where: (SqlExpressionBuilder.() -> Op<Boolean>)? = null,
    body: T.(UpdateStatement) -> Unit,
): Int {
    return this.update(where) {
        val now = Instant.now().toEpochMilli()
        val executorUser = Headers.USER_MAIL.getOrDefault()
        it[lastModifiedBy] = executorUser
        it[lastModifiedDate] = now
        body(it)
    }
}
BaseTable in inherited from LongIdTable which has lastModifiedDate etc.
🙏 1
4 Views