【问题标题】:Entity listener not called未调用实体侦听器
【发布时间】:2019-12-01 09:04:04
【问题描述】:

我有以下实体和关联的侦听器

@Entity
@EntityListeners(InjuryListener::class)
class Injury(val description: String,
             @Id @GeneratedValue(strategy = GenerationType.SEQUENCE) val id: Long = 0)

@Singleton
class InjuryListener : PreDeleteEventListener {
    @PreRemove
    fun preRemove(injury: Injury) {
        TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
    }

    override fun onPreDelete(event: PreDeleteEvent?): Boolean {
        val injury = event?.entity as Injury
        TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
    }
}

然而,当我删除一个 Injury 时,我的 InjuryListener 上的任何方法都没有被调用。关于为什么会这样的任何线索?

【问题讨论】:

  • 你是如何删除你的实体的?
  • 通过我定义为“@Repository interface InjuryRepository : CrudRepository”的存储库

标签: hibernate jpa kotlin micronaut micronaut-data


【解决方案1】:

正如 Ilya Dyoshin 所写,@EntityListener@PreRemove 未在 Micronaut Data 中使用。但是可以通过AOP技术解决。

首先使用您需要的预删除逻辑创建您自己的拦截器:

@Singleton
class InjuryPreDeleteInterceptor : MethodInterceptor<Injury, Boolean> {
    override fun intercept(context: MethodInvocationContext<Injury, Boolean>): Boolean {
        val injury = context.parameterValues[0] as Injury
        if (injury.someFlag) {
            // do not delete
        } else {
            // delete
            context.proceed()
        }
        return true
    }
}

然后创建将触发InjuryPreDeleteInterceptor的注解:

@MustBeDocumented
@Retention(RUNTIME)
@Target(AnnotationTarget.FUNCTION)
@Around
@Type(InjuryPreDeleteInterceptor::class)
annotation class VisitInjuryDelete

并将之前创建的@VisitInjuryDelete注解所注解的delete()方法签名添加到InjuryRepository接口中:

@VisitInjuryDelete
override fun delete(Injury entity)

您可以在此处找到有关 Micronaut 中 AOP 的更多信息:https://docs.micronaut.io/latest/guide/aop.html

【讨论】:

    【解决方案2】:

    只要您在 micronaut 世界中,大部分“魔法”都是在编译时完成的。 micronaut-data 的一个主要声明是不存在运行时元模型。

    这实际上意味着,您的实体上没有 EntityListener 注释。

    在 micronaut 世界中,您应该使用 DataInterceptor 来实现所需的功能。

    【讨论】:

    • 您有示例或可能的链接吗?我在 Google 上找不到太多信息
    猜你喜欢
    • 2012-04-30
    • 2019-07-25
    • 2019-01-26
    • 1970-01-01
    • 1970-01-01
    • 2012-04-08
    • 2017-09-24
    • 1970-01-01
    相关资源
    最近更新 更多