CDI Injecting services into JPA managed Entities

拟墨画扇 提交于 2019-12-23 15:19:00

问题


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
    }
}

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.


回答1:


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

So you will get

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


public class Audit {

    @Inject
    private Logger log;

    @Inject
    private Event<MyUniqueObjectEvent> events;

}

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.



来源:https://stackoverflow.com/questions/21743823/cdi-injecting-services-into-jpa-managed-entities

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!