dev.krud.crudframework.jpa.lazyinitializer.LazyInitializerPersistentHooks.kt Maven / Gradle / Ivy
package dev.krud.crudframework.jpa.lazyinitializer
import dev.krud.crudframework.crud.hooks.interfaces.CreateFromHooks
import dev.krud.crudframework.crud.hooks.interfaces.CreateHooks
import dev.krud.crudframework.crud.hooks.interfaces.IndexHooks
import dev.krud.crudframework.crud.hooks.interfaces.ShowByHooks
import dev.krud.crudframework.crud.hooks.interfaces.ShowHooks
import dev.krud.crudframework.crud.hooks.interfaces.UpdateFromHooks
import dev.krud.crudframework.crud.hooks.interfaces.UpdateHooks
import dev.krud.crudframework.jpa.lazyinitializer.annotation.InitializeLazyOn
import dev.krud.crudframework.model.BaseCrudEntity
import dev.krud.crudframework.modelfilter.DynamicModelFilter
import dev.krud.crudframework.ro.PagedResult
import dev.krud.crudframework.util.ReflectionUtils
import org.hibernate.Hibernate
class LazyInitializerPersistentHooks :
ShowHooks>,
ShowByHooks>,
IndexHooks>,
UpdateHooks>,
UpdateFromHooks>,
CreateHooks>,
CreateFromHooks> {
override fun onShow(entity: BaseCrudEntity?) {
entity ?: return
initializeLazyFields(entity) { it.show }
}
override fun onCreateFrom(entity: BaseCrudEntity, ro: Any) {
initializeLazyFields(entity) { it.createFrom }
}
override fun onCreate(entity: BaseCrudEntity) {
initializeLazyFields(entity) { it.create }
}
override fun onIndex(filter: DynamicModelFilter, result: PagedResult>) {
result.results ?: return
for (entity in result.results) {
initializeLazyFields(entity) { it.index }
}
}
override fun onShowBy(entity: BaseCrudEntity?) {
entity ?: return
initializeLazyFields(entity) { it.showBy }
}
override fun onUpdateFrom(entity: BaseCrudEntity, ro: Any) {
initializeLazyFields(entity) { it.updateFrom }
}
override fun onUpdate(entity: BaseCrudEntity) {
initializeLazyFields(entity) { it.update }
}
private fun initializeLazyFields(entity: BaseCrudEntity, condition: (annotation: InitializeLazyOn) -> Boolean) {
ReflectionUtils.doWithFields(entity::class.java) {
val annotation = it.getDeclaredAnnotation(ANNOTATION_TYPE) ?: return@doWithFields
if (condition(annotation)) {
ReflectionUtils.makeAccessible(it)
Hibernate.initialize(it.get(entity))
}
}
}
companion object {
private val ANNOTATION_TYPE = InitializeLazyOn::class.java
}
}
© 2015 - 2024 Weber Informatics LLC | Privacy Policy