CDI将服务注入JPA管理的实体 [英] CDI Injecting services into JPA managed Entities

查看:106
本文介绍了CDI将服务注入JPA管理的实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我确信这与这个问题有很大关系,但该问题的操作有一些情景我不确定甚至对于DI有意义。所以这是我的理解,尝试将JPA实体与CDI Bean混合通常不是一个好主意,因为两者通常都是通过创建代理对象来完成的。这是我的设想,但从我读过的这是不可能的。

I'm sure this is strongly related to this question but the op on that question has a bit of a scenario that I'm not sure even makes sense for DI. So here's what I understand, it's generally not a good idea to try to mix a JPA Entity with a CDI Bean because both are generally done by creating proxy objects. Here's what I envisioned, but from what I've read this is not possible.

@Entity
public class MyUniqueObject implements Serializable {

    @Inject
    private transient Logger log;

    @Inject
    private transient Event<MyUniqueObjectEvent> events;

    @Id
    private long id;

    @NotNull
    private String text;

    public void setText( final String text ) {
       log.debug( "updating text {}", this );
       this.text = text;
       events.fire( new MyUniqueObjectEvent( this ) ); // consumed by an @Observes method
    }
}

什么是 best 方式来做我想要完成的事情?这基本上是从JPA持久化实体中触发事件,访问日志对象等事情。代码示例很有用。

What's the best way to do what I'm trying to accomplish? which is fundamentally things like events firing from within JPA persisted entities, access to log objects. Code examples helpful.

推荐答案

我想知道观察实体属性的每一个变化是否真的有用,即使它们不会最终得到坚持。所以你不觉得实体监听器和回调函数

I am wondering if it's really useful to observe every change to entity attributes, even if they won't eventually get persisted. So don't you think that Entity Listeners and Callbacks woudn't be sufficient for you?They support CDI since JPA 2.1 and offer plenty of callbacks which you can observe


  • @PrePersist

  • @PreRemove

  • @PostPersist

  • @PostRemove

  • @ PreUpdate

  • @PostUpdate

  • @PostLoad
  • @PrePersist
  • @PreRemove
  • @PostPersist
  • @PostRemove
  • @PreUpdate
  • @PostUpdate
  • @PostLoad

所以你会得到

@EntityListeners(class=Audit.class)
@Entity
public class MyUniqueObject implements Serializable {}


public class Audit {

    @Inject
    private Logger log;

    @Inject
    private Event<MyUniqueObjectEvent> events;

}

现在您可以观察实体的生命周期 - 也是更好的是,你已经分离了你的模型和它的审计,你不需要搞定setter和getters(这很混乱)来实现日志记录。另请注意,您也可以为每个实体定义

Now you can observe the lifecycle of your entity - also it's better that you have separated your model and its auditing, you don't have to mess up with setters and getters (which is confusing) to achieve logging. Also note that you can also define Default Entity Listeners for every entity you have.

这篇关于CDI将服务注入JPA管理的实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆